创建动态类型集合和数组

本文关键字:数组 集合 类型 动态 创建 | 更新日期: 2023-09-27 18:15:54

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

public void AlphaToChar(iList _blah)
{
}

Out of IList我想提取它的成员类型,并使用它的类型在方法中创建其他数组或列表。

"List = new List();"部分不起作用,因为我假设它是类型变量,而不是实际类型。还有别的办法吗?如何完成此操作并创建提取类型的新集合?

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

谢谢。

创建动态类型集合和数组

您可以使用以下方法构建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将包含什么,并且您不必使用反射来确定其元素类型。

这将动态地为指定的元素类型构造一个通用的List<T>:

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

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

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