2010-07-29 57 views
1

我有一個輔助類,它在一個實體列表上做了一個簡單但重複的過程。爲簡單起見,是這樣的......一系列重載方法的替代

public static List<MyType> DoSomethingSimple(List<MyType> myTypes) { 
    return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList(); 
} 

我現在需要添加其他類型的支持,但一切是相同的......我該如何避免重載方法像這樣的增長列表:

public static List<MyType> DoSomethingSimple(List<MyType> myTypes) { 
    return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList(); 
} 

public static List<MyOtherType> DoSomethingSimple(List<MyOtherType> myOtherTypes) { 
    return myOtherTypes.Where(myOtherType => myOtherType.SomeProperty.Equals(2)).ToList(); 
} 

...等等。

+0

是在這兩種情況下從共同基類繼承的「SomeProperty」? – 2010-07-29 11:19:03

回答

4

這裏有兩種方式:

  1. 使用仿製藥,並共同基類
  2. 使用接口

方法1:

public class BaseClass 
{ 
    public int SomeProperty { get; set; } 
} 

public class MyType : BaseClass { } 
public class MyOtherType : BaseClass { } 

public class ClassWithMethod 
{ 
    public static List<T> DoSomethingSimple<T>(List<T> myTypes) 
     where T : BaseClass 
    { 
     return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList(); 
    } 
} 

方法2:

public interface ICommon 
{ 
    int SomeProperty { get; set; } 
} 

public class MyType : ICommon 
{ 
    public int SomeProperty { get; set; } 
} 

public class MyOtherType : ICommon 
{ 
    public int SomeProperty { get; set; } 
} 

public class ClassWithMethod 
{ 
    public static List<T> DoSomethingSimple<T>(List<T> myTypes) 
     where T : ICommon 
    { 
     return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList(); 
    } 
} 

現在,如果你嘗試使該方法直接使用界面,如下所示:

public class ClassWithMethod 
{ 
    public static List<ICommon> DoSomethingSimple(List<ICommon> myTypes) 
    { 
     return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList(); 
    } 
} 

然後,如果您在撥打電話時有List<ICommon>,那麼這將起作用,但如果您有List<MyType>則無效。

public class ClassWithMethod 
{ 
    public static List<ICommon> DoSomethingSimple(IEnumerable<ICommon> myTypes) 
    { 
     return myTypes.Where(myType => myType.SomeProperty.Equals(2)).ToList(); 
    } 
} 

注意,我改爲使用IEnumerable<ICommon>代替:在C#4.0中,如果我們稍微改變方法可以做到這一點。這裏的概念被稱爲共同和反方差,除此之外我不會多說這些。搜索堆棧溢出以獲取有關該主題的更多信息。

提示:我會改變輸入參數是IEnumerable<T>不管,因爲這會令你的方法更多的場合下使用,你可以有不同類型的集合,數組等。並且,只要它們含有正確的類型,它們可以傳遞給方法。通過將自己限制爲List<T>,可以強制代碼的用戶在某些情況下轉換爲列表。我的準則在輸入參數中應儘可能不明確,並儘可能在輸出參數中儘可能具體。

2

假設屬性對於每個列表類型相同的名稱和類型,你可以添加一個接口包含屬性,並實現它爲每種類型要調用此方法上:

public interface ISomeProperty 
{ 
    object SomeProperty { get; } 
} 

DoSomethingSimple可能再是:

public static List<T> DoSomethingSimple<T>(IEnumerable<T> list) where T : ISomeProperty 
{ 
    return list.Where(i => i.SomeProperty.Equals(2)).ToList(); 
}