【发布时间】:2016-01-09 00:06:44
【问题描述】:
我有一个需要以下定义的类:
public class Table<T> : ObservableCollection<T> where T : IRowDef, new()
我想创建它的集合并使用实例映射类型。所以我尝试:
public sealed class TableCollection : IEnumerable<Table<IRowDef>>
{
private Dictionary<Type, Table<IRowDef>> _tableDictionary;
public Table<IRowDef> GetTable<T>() where T : IRowDef, new()
{
Table<IRowDef> table = null;
if (_tableDictionary.ContainsKey(typeof(T)))
{
table = _tableDictionary[typeof(T)];
}
else
{
table = new Table<IRowDef>();
_tableDictionary.Add(typeof(T), table);
}
return table;
}
...
}
但我不能让它工作。以下几行和其他几行给出了相同的错误:
private Dictionary<Type, Table<IRowDef>> _tableDictionary;
翻译后的错误告诉 IRowDef 必须是非抽象的并且具有无参数的构造函数。我知道它来自 Table 类定义的“new()”类型限制,但它是此类内部代码所必需的。我知道我可以通过使用包含无参数构造函数的特定类类型来解决这个问题,例如:
private Dictionary<Type, Table<ClientTable>> _tableDictionary;
但必须支持不同类型的表,这也是它们都实现 IRowDef 的原因。
有人知道我该如何解决这个问题吗?
【问题讨论】:
-
为什么不使用
Dictionary<Type, object>并在需要时进行转换?
标签: c# generics collections covariance