在数组中保存开放的泛型类型?
时间:2020-03-05 18:52:02 来源:igfitidea点击:
我遇到了.NET泛型的问题。我想做的是保存泛型类型(GraphicsItem)的数组:
public class GraphicsItem<T> { private T _item; public void Load(T item) { _item = item; } }
如何将这样的开放泛型类型保存在数组中?
解决方案
回答
如果要存储异构的GrpahicsItem的即GraphicsItem <X>和GrpahicsItem <Y>,则需要从通用基类派生它们,或者实现通用接口。另一种选择是将它们存储在List <object>中
回答
我们是否试图以非泛型方法创建GraphicsItem数组?
我们不能执行以下操作:
static void foo() { var _bar = List<GraphicsItem<T>>(); }
然后稍后填写列表。
我们是否更有可能尝试执行此类操作?
static GraphicsItem<T>[] CreateArrays<T>() { GraphicsItem<T>[] _foo = new GraphicsItem<T>[1]; // This can't work, because you don't know if T == typeof(string) // _foo[0] = (GraphicsItem<T>)new GraphicsItem<string>(); // You can only create an array of the scoped type parameter T _foo[0] = new GraphicsItem<T>(); List<GraphicsItem<T>> _bar = new List<GraphicsItem<T>>(); // Again same reason as above // _bar.Add(new GraphicsItem<string>()); // This works _bar.Add(new GraphicsItem<T>()); return _bar.ToArray(); }
请记住,我们将需要通用类型引用来创建通用类型的数组。这可以在方法级别(在方法之后使用T)或者在类级别(在类之后使用T)。
如果希望该方法返回GraphicsItem和GraphicsItem的数组,则让GraphicsItem从非通用基类GraphicsItem继承并返回该数组。但是,我们将失去所有类型的安全性。
希望能有所帮助。
回答
实现一个非通用接口,并使用该接口:
public class GraphicsItem<T> : IGraphicsItem { private T _item; public void Load(T item) { _item = item; } public void SomethingWhichIsNotGeneric(int i) { // Code goes here... } } public interface IGraphicsItem { void SomethingWhichIsNotGeneric(int i); }
然后将该接口用作列表中的项目:
var values = new List<IGraphicsItem>();