c# - 有类型<>/无类型设计

标签 c# oop design-patterns generics

我有一个(现有的)类型化的项目类:

Items<T>
    T Value { get; }

T 可以是 double、string 或 int。

然后我有一个必须包含多个 Items 实例的类。在此类的单个实例中,T 始终相同。就目前而言,实际包含的类型是由一个属性决定的,容器没有类型:

Data
    DataType { get; set; }
    Items<double>
        double Value;
    Items<string> 
        // ... and so on. Nasty stuff.

理想情况下,当然是

Data<T>
    Items<T>
        T value

数据实例是在代码中从头开始创建的,可以从数据库中加载。所以我们的 future 当然会有工厂,但是 Create 方法的返回类型是什么?

更糟糕的是,我需要这个:

DataCollection
    // HERE'S THE PAIN: What's the type here?
    List of Data<> instances with differing types

foreach (? data in someDataCollection)
    if (thetypeof data is double)
        doSomething();
    else
        doSomethingElse();

现在,我可以解决这个问题,但我看不到一个干净的方法来解决这个问题。

我的第一个问题是 DataCollection 的声明。列表的类型是什么? List,所以它可以容纳 Data 和 Data?

最佳答案

实际上有一种干净的方法可以解决这个问题;您可以使用带有数据类型键和泛型 Func<> 值的字典。然后您将该类型传递给您的创建方法,该方法然后根据类型查找要在 Dictionary 中使用的 Func<>,并调用该 Func<> 来创建或处理您的对象。

因为我是用伪代码工作的,基本上它看起来像下面这样;您可以使用它并修改它以满足您的需求,但这是基本思想。

首先,为所有数据对象创建一个父类;请注意,此类有一个查找字典,用于在各种类型上调用的函数,并注意它是抽象的:

public abstract class Data
{

    // A Lookup dictionary for processing methods
    // Note this the functions just return something of type object; specialize as needed
    private static readonly IDictionary<Type, Func<object, Data>> _processFunctions = new Dictionary
        <Type, Func<object, Data>>()
         {
             {typeof(int), d => { return doSomethingForInt( (Data<int>) d); }},
             {typeof(string), d => { return doSomethingForString( (Data<string>) d); }},
             {typeof(double), d => { return doSomethingForDouble( (Data<double>) d); }},

         };

    // A field indicating the subtype; this will be used for lo
    private readonly Type TypeOfThis;

    protected Data(Type genericType)
    {
        TypeOfThis = genericType;
    }

    public Data Process()
    {
        return _processFunctions[this.TypeOfThis](this);
    }

}

现在使用可以实例化的通用类型对 Data 进行子类化:

class Data<T> : Data
{

    // Set the type on the parent class
    public Data() : base(typeof(T))
    {
    }

    // You can convert this to a collection, etc. as needed
    public T Items { get; set; }

    public static Data<T> CreateData<T>()
    {
        return new Data<T>();
    }
}

然后您可以使用父类型创建一个 DataCollection 类。注意 ProcessData() 方法;它现在所做的就是遍历元素并在每个元素上调用 Process():

class DataCollection
{
    public  IList<Data> List = new List<Data>();

    public void ProcessData()
    {
        foreach (var d in List)
        {
            d.Process();
        }
    }

}

...一切就绪!现在您可以使用不同类型的数据调用您的 DataCollection:

DataCollection dc = new DataCollection();

dc.List.Add(new Data<int>());
dc.List.Add(new Data<string>());
dc.List.Add(new Data<double>());


dc.ProcessData();

关于c# - 有类型<>/无类型设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5569948/