加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:22:01 所属栏目:百科 来源:网络整理
导读:我有一个类需要以下定义: public class TableT : ObservableCollectionT where T : IRowDef,new() 我想创建它的集合并使用实例映射类型.所以我尝试: public sealed class TableCollection : IEnumerableTableIRowDef{ private DictionaryType,TableIRowDef
我有一个类需要以下定义:

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()”类型限制,但是这个类中的代码需要它.我知道我可以通过使用包含参数less constructor的特定类类型来解决这个问题,例如:

private Dictionary<Type,Table<ClientTable>> _tableDictionary;

但是必须支持不同类型的表,这就是为什么所有这些表都实现IRowDef的原因.

有谁知道我怎么解决这个问题?

解决方法

问题是你需要一组表,但是表< X>与表< Y>不相容和WhateverCollection< Table< X>>即使X是接口类型且Y实现此接口,也与WhateverCollection< Table< Y>>不兼容.

为什么呢?假设你有

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

Put that in your pipe and smoke it!

06001

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接口而不是Table基类,并让Table< T>实现ITable然后将字典声明为Dictionary< Type,ITable>.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读