2013-09-11 39 views
0

初学者的集合: 想写返回一个泛型集合的方法:如何返回基于输入(通用)

public IEnumerable<T> ABC(string x){ 

if(x== "1") 
{ Collection<A> needs to be returned} 

if(x=="2") 
{ Collection<B> needs to be returned} 
.. 
so on 
} 

问题: - 基于传递给方法“X”不同类型的集合被初始化并需要返回?我怎样才能做到这一点? - 这是正确的方法吗? - 可以获得更多通用用途细节的链接?

回答

1

AFAIK,类型参数(这里是T)必须在编译时已知。这意味着它在运行时不能改变。你可以做的是做到IEnumerable<Object>。由于每个其他类型都有Object作为基本类型,所以我很肯定你可以在那个时候返回一个IEnumerable。尽管您可能需要在路上投入/运出Object。

0

不需要传递字符串来标识类的类型。只需调用下面的泛型方法,它就会初始化那个T类型的List。

 /// <summary> 
     /// Gets the initialize generic list. 
     /// </summary> 
     /// <typeparam name="T"></typeparam> 
     public IList<T> GetInitializeGenericList<T>() where T : class 
     { 
      Type t = typeof(List<>); 
      Type typeArgs =typeof(T); 
      Type type = t.MakeGenericType(typeArgs); 
      // Create the List according to Type T 
      dynamic reportBlockEntityCollection = Activator.CreateInstance(type); 

      // If you want to pull the data into initialized list you can fill the data 
      //dynamic entityObject = Activator.CreateInstance(typeArgs); 

      //reportBlockEntityCollection.Add(entityObject); 

      return reportBlockEntityCollection; 
     } 
+0

为什么不使用'return new List ();'而不是使用激活器,如果你打算使用泛型? (也许我只是错过了一些东西。) –

+0

是的,如果你想只是初始化T的列表,你可以返回新的列表()。但如果你需要添加一些数据到它,那么它在这种情况下失败。您不能创建使用泛型的实例。 –

+0

当然可以。取一个“T”的实例(或集合),并在“新建”集合中使用'.Add()'或'AddRange()'。 –