gpt4 book ai didi

c# - 一系列重载方法的替代方案

转载 作者:太空宇宙 更新时间:2023-11-03 19:33:41 25 4
gpt4 key购买 nike

我有一个帮助程序类,它对实体列表执行简单但重复的过程。为了简单起见,它是这样的......

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();
}

...等等。

最佳答案

两种方式:

  1. 使用泛型和通用基类
  2. 使用接口(interface)

方法一:

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();
}
}

方法二:

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();
}
}

现在,如果您尝试让方法直接使用接口(interface),如下所示:

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

那么如果你有一个 List<ICommon> 就可以了当你调用它时,但如果你有 List<MyType> 则不会工作.在 C# 4.0 中,如果我们稍微改变一下方法就可以做到这一点:

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

请注意,我改为使用 IEnumerable<ICommon>反而。这里的概念叫做协方差和逆方差,除此之外我就不多说了。搜索 Stack Overflow 以获取有关该主题的更多信息。

提示:我会将输入参数更改为 IEnumerable<T>不管怎样,因为这会使您的方法在更多实例中可用,您可以有不同类型的集合、数组等,只要它们包含正确的类型,就可以将它们传递给该方法。通过将自己限制在 List<T>在某些情况下,您强制代码的用户转换为列表。我的准则是在输入参数中尽可能不具体,在输出参数中尽可能具体。

关于c# - 一系列重载方法的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3361891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com