我需要编写一个泛型类,其中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不能是派生类,否则编译器不会将其识别为另一个的元素.