Skip to main content
 首页 » 编程设计

c#之创建动态类型集合和数组

2024年01月29日29zfyouxi

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

public void AlphaToChar(iList _blah) 
{ 
 
} 

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

“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是什么将包含,您不必使用反射来确定其元素类型。