在列表中选择与接口匹配的项目 [英] Select items in List that match an interface
本文介绍了在列表中选择与接口匹配的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我定义了以下接口:
public interface IStep
{
string Name { get; set; }
}
public interface IStepBuildDataSet : IStep
{
DataSet Data { get; set; }
}
public interface IStepBuildFile : IStep
{
byte File { get; set; }
}
我有使用这些接口的代码:
I have code that uses these interfaces:
public List<IStep> Steps { get; set; }
public void RunJob()
{
// pseudo code, need to update:
IStepBuildDataSet buildDataSet = Steps.Single(s => s is IStepBuildDataSet);
IStepBuildFile buildFile = Steps.Single(s => s is IStepBuildFile);
// call methods on Steps
}
替换伪代码的正确语法是什么?我想从清单中获得实现certian接口的步骤.列表中只有一个.
What is the correct syntax for to replace the Pseudo Code? I want to get the step in the list that implements a certian interface. There will only be one of each in the list.
推荐答案
您可以使用OfType使其变得更加干净:
You could use OfType to make it abit cleaner like this:
IStepBuildDataSet buildDataSet = Steps.OfType<IStepBuildDataSet>().Single();
IStepBuildFile buildFile = Steps.OfType<IStepBuildFile>().Single();
请注意,由于OfType可以帮您实现结果,因此您无需投放结果.
Notice, you dont need to cast the results, since OfType does that for you.
这篇关于在列表中选择与接口匹配的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文