如何根据输入返回集合(通用)

时间:2013-09-11 00:03:54

标签: c# .net

初​​学者: 想写一个方法来返回一个泛型集合:

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”,不同类型的集合被初始化并需要返回?我怎样才能做到这一点? - 这是正确的方法吗? - 获取有关通用用法的更多详细信息的任何链接?

2 个答案:

答案 0 :(得分:1)

AFAIK,类型参数(此处为T)必须在编译时知道。这意味着它在运行时无法改变。你能做的就是把它IEnumerable<Object>。因为每个其他类型都有Object作为基类型,所以我很确定你可以在那时返回任何IEnumerable。虽然您可能需要在途中投入/投出Object。

答案 1 :(得分: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;
        }
相关问题