创建动态类型集合和数组

时间:2011-11-28 19:58:27

标签: c# .net list sorting interface

假设我有一个接口传递给我的方法:

public void AlphaToChar(iList _blah)
{

}

在IList之外我想提取它的成员类型并使用它的类型在方法中创建其他数组或列表。见下面的例子。

“List = new List();” part不起作用,因为我认为它是一个类型变量,而不是实际类型。 有什么方法吗?如何完成此操作并创建一个提取类型的新集合?

Type[] listTypes =  list.GetType().GetGenericArguments();
Type listType = null;
if (listTypes.Length>0)
{
   listType = listTypes[0];
}
List<listType> = new List<listType>();

谢谢。

3 个答案:

答案 0 :(得分:4)

您可以使用以下内容进行List<>构建:

// Find the generic argument type of your old list (theList)
Type genericType = theList.GetType().GetGenericArguments()[0];

// Create a new List with the same generic type as the old one
Type newListType = typeof(List<>).MakeGenericType(genericType);

// Create a new instance of the list with the generic type
var instance = Activator.CreateInstance(newListType);

但是只有在使用通用列表时它才会起作用。您提供的示例是使用常规IList。您必须更改方法签名才能使用通用IList<>

public void AlphaToChar(IList<Something> _blah) { }

或者说它更通用:

public void AlphaToChar<T>(IList<T> _blah) /* where T : ISomething, new() */ {}  

如果不这样做,你应该知道你的IList将包含什么,你不必使用反射来弄清楚它的元素类型是什么。

答案 1 :(得分:2)

这为指定的元素类型动态构造通用List<T>

IList list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(elementType));

请注意,结果变量不是静态类型到专用列表,因为您在编译时不知道类型。因此,它不可能是静态类型的。您正在利用List<T>在此处实施IList的事实。

答案 2 :(得分:0)

System.Collections.IList list = 
Activator.CreateInstance(typeof(List<>)
.MakeGenericType(listTypes[0])) as System.Collections.IList;
相关问题