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

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

概述我需要编写一个泛型类,其中type参数必须是实现ICollection< T>的东西.在MyClass中我需要集合的项类型(在标记为???的代码片段中). class MyClass<TCollection> where TCollection : ICollection<???>{ // ... public void store(??? obj) { /* put obj into 我需要编写一个泛型类,其中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不能是派生类,否则编译器不会将其识别为另一个的元素.

总结

以上是内存溢出为你收集整理的C#中的泛型类型:将类型参数限制为集合全部内容,希望文章能够帮你解决C#中的泛型类型:将类型参数限制为集合所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1221461.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存