gpt4 book ai didi

c# - 受限类型的通用集合

转载 作者:行者123 更新时间:2023-11-30 12:42:37 26 4
gpt4 key购买 nike

我有一个类需要以下定义:

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 的原因。

有人知道我该如何解决这个问题吗?

最佳答案

问题是您需要一组表,但是 Table<X>Table<Y> 不兼容和一个 WhateverCollection<Table<X>>WhateverCollection<Table<Y>> 不兼容, 即使X是一个接口(interface)类型并且Y实现这个接口(interface)。

为什么会这样?假设你有

List<IAnimal> animals = new List<Elefant>();
animals.Add(giraffe); // Ooops!

Put that in your pipe and smoke it!

// DOES NOT WORK!  
T<Base> b = new T<Derived>(); // T<Derived> is not assignment compatible to T<Base>!!!

但是

Base b = new Derived(); // OK

诀窍是有两个表类:一个非泛型基类和一个派生泛型类:

public abstract class Table
{}

public class Table<T> : Table
where T : IRowDef, new()
{
private readonly ObservableCollection<T> _rows = new ...;
}

现在你可以声明一个

private Dictionary<Type, Table> _tableDictionary;

或者如果你想坚持从一个可观察的集合派生,声明一个(非通用!)ITable接口(interface)而不是 Table基类并让 Table<T>实现 ITable然后将字典声明为 Dictionary<Type, ITable> .

关于c# - 受限类型的通用集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33065411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com