处理在运行时基于数据库数据实例化的泛型类

本文关键字:数据 实例化 泛型类 数据库 运行时 处理 | 更新日期: 2023-09-27 18:18:14

我有一个问题,我的泛型类和创建它们在运行时,基于位于数据库中的数据。在下面的例子中,我试图给出一个简单的例子,用一个泛型计数器类跟踪一个值在列中出现的频率。

Counter是泛型类,类Table模拟有两列的数据库表,Wrapper类包含问题:()

基本上包装器类为我的数据库提供了一个与DBMS无关的接口,并向应用程序公开功能器。请注意,我知道我的列具有哪些数据类型,但是如何提供对计数器对象的通用访问呢?
public class Counter<T>
{
    private Dictionary<T, int> _counter = new Dictionary<T,int>();
    public Counter() {}
    public Counter(List<T> values) : this()
    {
        foreach (var item in values)
            this.Add(item);
    }
    public void Add(T key)
    {
        if (!this._counter.ContainsKey(key))
            this._counter[key] = 0;
        this._counter[key] += 1;
    }
    public int GetCount(T key)
    {
        return this._counter[key];
    }
}
public class Table
{
    public List<int> IDs { get; private set; }
    public List<String> Names { get; private set; }
    public Table()
    {
        this.IDs = new List<int> { 1, 2, 3, 4, 5 };
        this.Names = new List<string> { "a", "b", "a", "c", "d" };
    }
}
public class Wrapper
{
    private Table _table = new Table();
    public ... GetCounter(string columnName)
    {
        if (columnName == "id")
            return new Counter<..>(this._table.IDs);
        else if (columnName == "name")
            return new Counter<..>(this._table.Names);
    }
}

处理在运行时基于数据库数据实例化的泛型类

您可以将GetCounter方法更改为泛型函数:

public Counter<T> GetCounter<T>(string columnName)
{
    if (columnName == "id")
        return new Counter<T>(this._table.IDs);
    else if (columnName == "name")
        return new Counter<T>(this._table.Names);
}