我有幾個不同的類型都具有一個共同的特性:C#方法採取的類型列表以相同的屬性
public class A {
public int SomeCommonProperty { get; set; }
/*
* some other stuff
*/
}
public class B {
public int SomeCommonProperty { get; set; }
/*
* some other stuff
*/
}
我想有需要的這些對象的列表與此屬性的方法這樣我可以遍歷列表和財產比較喜歡另一個參數:
public static List<T> MethodToTakeListOfAboveTypes<T>(this List<T> destinationList, List<T> sourceList, string someProp)
{
if (sourceList != null && sourceList.Exists(tab => tab.SomeCommonProperty == someProp))
{
destinationList = sourceList.Where(tab => tab.SomeCommonProperty == someProp).ToList();
}
return destinationList;
}
爲T沒有「SomeCommonProperty」的定義,這是有道理的上面的代碼不起作用。 我只想傳遞一個更通用的對象與該屬性,以便我不必爲每種類型創建相同的方法。我只是無法獲得正確的語法。這有意義嗎?
我知道我應該把SomeCommonProperty字段放入一個基類並繼承,但由於某種原因,這似乎不起作用。
繼承是專門爲處理這種情況而設計的。你爲什麼認爲它「似乎不起作用」? – 2014-10-28 21:21:44