【发布时间】:2015-03-22 20:00:52
【问题描述】:
在我的一个项目的开发过程中,我遇到了一个关于泛型类型的问题。
该项目要求我编写一个作为列表对象来源的类。假设我有以下课程:
public class TablesProvider
{
private readonly List[] _tables;
public TablesProvider()
{
// initialize the tables var here....
}
public List<TItem> GetTable<TItem>()
{
return (List<TItem>)_tables.Single(x => x is List<TItem>);
}
}
这个类显然不起作用,因为List 类型是泛型类型,因此应该指定泛型参数。
所以我创建了一个名为 MyList 的抽象类型,它会由更具体的类型 MyList<TItem> 派生,以逃避这个要求,并稍微编辑了 TablesProvider。
public class TablesProvider
{
private readonly MyList[] _tables;
public TablesProvider()
{
// initialize the tables var here....
}
public MyList<TItem> GetTable<TItem>()
{
return (MyList<TItem>)_tables.Single(x => x is MyList<TItem>);
}
}
public abstract class MyList
{
// ...
}
public class MyList<TItem> : MyList, IList<TItem>
{
private readonly List<TItem> _elements = new List<TItem>();
public TItem this[int index]
{
get { return _elements[index]; }
set { _elements[index] = value; }
}
// ...
}
这很好用。只剩下一个问题了。假设我有 45 个不同的集合,每个集合都用不同的通用参数定义。初始化所有这些集合的最佳方法是什么?我不能在这里使用 for 循环,因为泛型参数是在编译时而不是在运行时指定的,因此这样的构造是不可能的:
for (int i = 0; i < 45; i++)
_tables[i] = new MyList<GenericParameters[i]>();
我的最终目标是有幸去做这样的事情......
var table = _tablesProvider.GetTable<SomeClass>();
var element = table[3];
var propertyValue = element.SomeProperty;
...无需强制转换变量element 即可访问其特定类型的成员。
可能值得一提的是,不同列表对象的数量固定为 45。这不会改变。理论上,我可以逐行初始化数组,或者改为使用 45 个属性或变量。然而,这两种选择对我来说都是一种相当便宜的解决方案,但如果没有其他方法,我会接受其中一种。
你们有什么想法吗?我这样做完全错了吗?我应该考虑其他结构吗?
提前致谢。
【问题讨论】:
标签: c# oop generics collections