2010-07-29 58 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(); 
}