处理在运行时基于数据库数据实例化的泛型类
本文关键字:数据 实例化 泛型类 数据库 运行时 处理 | 更新日期: 2023-09-27 18:18:14
我有一个问题,我的泛型类和创建它们在运行时,基于位于数据库中的数据。在下面的例子中,我试图给出一个简单的例子,用一个泛型计数器类跟踪一个值在列中出现的频率。
类Counter
是泛型类,类Table
模拟有两列的数据库表,Wrapper
类包含问题:()
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);
}