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

C#中的泛型类型:将类型参数限制为集合

发布时间:2020-12-15 23:53:35 所属栏目:百科 来源:网络整理
导读:我需要编写一个泛型类,其中type参数必须是实现ICollection T的东西.在MyClass中我需要集合的项类型(在标记为???的代码片段中). class MyClassTCollection where TCollection : ICollection???{ // ... public void store(??? obj) { /* put obj into collect
我需要编写一个泛型类,其中type参数必须是实现ICollection< T>的东西.在MyClass中我需要集合的项类型(在标记为???的代码片段中).

class MyClass<TCollection> where TCollection : ICollection<???>
{
  // ...

  public void store(??? obj) { /* put obj into collection */ }

  // ...
}

通常该集合实际上是字典.有时,它会像列表一样简单.

我确切知道如何在C中做到这一点.我怎么做这个是C#?

解决方法

最简单的方法是仅指定元素类型并硬编码ICollection< T>无论你需要什么,例如

class MyClass<T> {

    private ICollection<T> _items;

    public MyClass(ICollection<T> items) {
        _items = items;
    }

    public void Store(T obj) {
        _items.Add(obj);
    }

    public ICollection<T> Items {
        get {
            return _items;
        }
    }
}

我建议您将集合实例传递给构造函数,而不是在内部创建一个.它使类更简单,更“通用”(借口双关语),并允许您使用非默认构造函数构造集合实例,例如带有非默认比较器的字典.

RE-EDIT(第三次尝试):使用类继承和命名空间别名来模拟typedef都可以达到一定程度,但在某些情况下两个抽象都会崩溃.这段代码是我发现的最简单的实际编译代码.

第1步 – 定义这些类:

// This KeyValuePair was being used to simulate a tuple. We don't need to simulate a tuple when we have a concrete class.
class BazAndListOfWrgl {
    Baz Baz { get; set; }
    List<Wrgl> Wrgls { get; set; }
}

// Simple typedef.
class BazAndListOfWrglDictionary : Dictionary<Bar,BazAndListOfWrgl> { }

第2步 – 定义这些命名空间别名.所有标识符必须完全合格.引用的所有类型必须已在不同的物理文件中定义(因为名称空间别名必须在文件中的所有代码之前).

using OuterDictionary = System.Collections.Generic.Dictionary<MyNamespace.Foo,MyNamespace.BazAndListOfWrglDictionary>;
using OuterDictionaryItem = System.Collections.Generic.KeyValuePair<MyNamespace.Foo,MyNamespace.BazAndListOfWrglDictionary>;

第3步 – 像这样使用它们:

class Program {

    static void Main() {

        // List-based example.
        var listWrapper = new MyClass<BazAndListOfWrgl>(new List<BazAndListOfWrgl>());
        listWrapper.Store(new BazAndListOfWrgl());
        Console.WriteLine(listWrapper.Items.Count);

        // Dictionary-based example.
        var dictionaryWrapper = new MyClass<OuterDictionaryItem>(new OuterDictionary());
        dictionaryWrapper.Store(new OuterDictionaryItem(new Foo(),new BazAndListOfWrglDictionary()));
        Console.WriteLine(dictionaryWrapper.Items.Count);

    }
}

原因是:BazAndListOfWrglDictionary不能是命名空间别名,因为命名空间别名不能相互依赖. OuterDictionary和OuterDictionaryItem不能是派生类,否则编译器不会将其识别为另一个的元素.

(编辑:李大同)

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

    推荐文章
      热点阅读