【问题标题】:Saving an open generic type in an array?在数组中保存一个开放的泛型类型?
【发布时间】:2008-09-12 05:52:05
【问题描述】:

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

public class GraphicsItem<T>
{
    private T _item;

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

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

【问题讨论】:

    标签: .net generics


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      如果你想存储异构的 GrpahicsItem,即 GraphicsItem 和 GrpahicsItem,你需要从公共基类派生它们,或者实现公共接口。另一种选择是将它们存储在 List

      【讨论】:

        【解决方案3】:

        您是否尝试在非泛型方法中创建一个 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 继承并返回该数组。但是,您将失去所有类型安全性。

        希望对您有所帮助。

        【讨论】:

          猜你喜欢
          • 2011-07-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-05
          • 1970-01-01
          • 2021-06-01
          • 2021-10-31
          • 1970-01-01
          相关资源
          最近更新 更多