我面临 .NET 泛型的问题。我想做的事情是保存一个泛型类型数组(GraphicsItem):

public class GraphicsItem<T>
{
    private T _item;

    public void Load(T item)
    {
        _item = item;
    }
}

如何将这种开放泛型类型保存在数组中?

有帮助吗?

解决方案

实现一个非通用接口并使用它:

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>();

其他提示

如果您想存储异构 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 继承并返回该数组。不过,您将失去所有类型安全性。

希望有帮助。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top