在 C# 中创建仅适用于特定类型的通用函数

Creating a generic function in c# that only works with specific types

我正在尝试创建一个通用函数来处理我的两个模型中的任何一个。请注意,这两个模型具有完全相同的属性...

例如,在下面的代码中,即使 'NewProduct' 和 'OldProduct' 都有这个 属性.如何向 VS 指定我希望能够传入的两种类型? IList<NewProduct>, IList<OldProduct>

public static IList<T> GenericFunction<T>(IList<T> objList)
{
    IList<T> filteredData = objList.Where(p => p.Price > 0));
}

您应该研究抽象 classes、扩展和多态性。制作一个带有价格变量的抽象 class,然后从中扩展您的两个 class。然后使用抽象class作为参数。

两种类型需要相同的接口或公共基础 class,此处称为 ProductBase。然后,您可以使用带有 where 关键字的通用约束:

public static IList<T> GenericFunction<T>(IList<T> objList) 
  where T : ProductBase
{
    IList<T> filteredData = objList.Where(p => p.Price > 0));
}

这有效,如果 ProductBase 定义了一个 属性 Price

为了使其正常工作,您需要一个通用基础 class 或在两种产品类型中实现的通用接口。

public interface IProduct
{
    string Name { get; set; }
    decimal Price { get; set; }
}

然后可以加一个generic type constraint:

public static IList<P> GenericFunction<P>(IList<P> objList)
    where P : IProduct // Here you can specify either the base class or the interface.
{
    return objList
        .Where(p => p.Price > 0)
        .ToList();
}    

现在 C# 知道泛型类型 P 具有 NamePrice 属性。


注意:相反,您可以只输入参数列表和 return 类型 IList<IProduct>;但是,IList<OldProduct>IList<NewProduct> 与之兼容的赋值。


更新: 如果泛型具有默认构造函数(即具有空参数列表或根本没有显式构造函数声明的构造函数),则可以实例化泛型类型。然后,您需要将 new() 添加到泛型类型约束中:

where P : IProduct, new()

然后您可以简单地创建一个新对象:

P newObject = new P();

您可以使用 where 泛型约束 https://msdn.microsoft.com/en-us/library/bb384067.aspx

您需要一些共同的基础 class 或它们都 extend/implement 的接口。您可以定义多个约束,但它们必须相关。

interface IProduct
{
    double Price { get; }
}

public static IList<T> GenericFunction<T>(IList<T> objList) where T : IProduct
{
    IList<T> filteredData = objList.Where(p => p.Price > 0));
}

你应该为此使用一个接口。使用您需要的属性创建接口:

public interface MyInterface
{
    string Name { get; set; }
    string Color { get; set; }
}

这些属性应该是您的模型共有的。然后在你的模型中你必须实现接口:

public class MyModel : MyInterface

然后制定你的方法:

public void MyFunction(List<MyInterface> myModel)