2014-09-04 97 views
2

我有以下的接口定義的接口:在列表中選擇項目匹配

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

public interface IStepBuildDataSet : IStep 
{ 
    DataSet Data { get; set; } 
} 

public interface IStepBuildFile : IStep 
{ 
    byte File { get; set; } 
} 

我有一個使用這些接口代碼:

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接口的列表中找到步驟。列表中只會有一個。

+4

該代碼是正確的,你只需要強制轉換結果:'Steps.Single(S => s是IStepBuildDataSet)作爲IStepBuildDataSet' – 2014-09-04 23:16:54

+0

有道理,它返回一個ISTEP。如果您將其作爲答案發布,我會將其標記爲正確。謝謝。 – Josh 2014-09-04 23:20:17

+0

CSharpie的答案有同樣的效果,但LINQier,我會去那個。它有使過濾器更加明確的好處。 – 2014-09-05 00:26:03

回答

7

你可以使用OfType使它升技吸塵器這樣的:

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

注意,你不需要投的結果,因爲OfType會替你。

+1

好的方法,比我的表達更清潔。 – Josh 2014-09-04 23:22:18

+0

這太棒了。我甚至不知道OfType存在! – 2015-10-21 23:22:08

0

您有IStep的列表,因此列表中可能有不止一種不同類型的Istep對象。所以最好在foreach循環中完成。

foreach(IStepBuildDataSet buildDataSet in Steps.OfType<IStepBuildDataSet>()) 
{ 
    //do something here. 

} 

foreach(IStepBuildFile buildFile in Steps.OfType<IStepBuildFile>()) 
{ 
    //do something here. 

} 
+0

函數Single()存在的原因。 – CSharpie 2014-09-05 06:48:50