Select items in List that match an interface

前端 未结 2 1971
误落风尘
误落风尘 2021-01-07 00:52

I have the following Interfaces defined:

public interface IStep 
{
    string Name { get; set; }
}

public interface IStepBuildDataSet : IStep
{
    DataSet          


        
相关标签:
2条回答
  • 2021-01-07 01:07

    You could use OfType to make it abit cleaner like this:

    IStepBuildDataSet buildDataSet = Steps.OfType<IStepBuildDataSet>().Single();
    IStepBuildFile buildFile = Steps.OfType<IStepBuildFile>().Single();
    

    Notice, you dont need to cast the results, since OfType does that for you.

    0 讨论(0)
  • 2021-01-07 01:30

    You have list of IStep, so there could be more than one of different types of Istep objects in the list. so it's better to do it in the foreach loop.

    foreach(IStepBuildDataSet buildDataSet in Steps.OfType<IStepBuildDataSet>())
    {
        //do something here.
    
    }
    
    foreach(IStepBuildFile buildFile in Steps.OfType<IStepBuildFile>())
    {
        //do something here.
    
    }
    
    0 讨论(0)
提交回复
热议问题