【问题标题】:Generic collection of generic types泛型类型的泛型集合
【发布时间】:2014-08-22 05:16:21
【问题描述】:

我想知道最好的方法是什么 要解决这个问题:

object GetCollection(T1, T2) 
{
    return new T1<T2>;
}

好吧,我知道这不会编译,但它说明了我的观点。 我需要基于通过 T1 的泛型类型创建一个集合类型,它应该包含 T2 类型的元素,

有什么想法吗? 提前致谢

【问题讨论】:

  • 你正在做new T1,但是你......需要创建一个集合类型......所以这个例子并没有说明你的观点。请详细说明一下。你是在T1 上做某种if-else 还是在T2 上做if-else?

标签: c# .net generics


【解决方案1】:

你的意思是这样的?

object GetCollection<T1, T2>() where T1 : IEnumerable<T2>, new()
{
    return new T1();
}

如果您在编译时不知道类型,那么您需要将泛型类型与反射绑定。 This Microsoft article may cover your needs.

【讨论】:

    【解决方案2】:

    你可以通过反射来做到这一点。否则,我会建议使用基于 T1 列表的接口。 像这样的:

    class GenericContainerOne<T> { }
    
    class GenericContainerTwo<T> { }
    
    class Construct { }
    
    static void Main(string[] args)
    {
        GenericContainerOne<Construct> returnObject = (GenericContainerOne<Construct>)GetGenericObject(typeof(GenericContainerOne<>), typeof(Construct));
    }
    
    static object GetGenericObject(Type container, Type construct)
    {
        Type genericType = container.MakeGenericType(construct);
    
        return Activator.CreateInstance(genericType);
    }
    

    【讨论】:

      【解决方案3】:

      最简单的是这样的:

      object GetCollection<T1, T2>() 
      {
          return Activator.CreateInstance(typeof(T1).MakeGenericType(typeof(T2)));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-11
        • 2021-12-04
        • 2017-12-24
        • 1970-01-01
        • 2011-04-16
        • 1970-01-01
        相关资源
        最近更新 更多