How to determine the type parameters of the generic List
When using reflection and manipulating collections, it is crucial to determine the type parameters of the generic List
The original code with the problem
Consider the following code:
<code class="language-csharp">foreach (PropertyInfo pi in lbxObjects.SelectedItem.GetType().GetProperties()) { switch (pi.PropertyType.Name.ToLower()) { case "list`1": // 如果 List<T> 包含元素,则此方法有效。 Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null)); // 但如果值为 null,如何获取类型? } }</code>
In this code, the GetGenericType method is used to get the type parameter, but it requires the list to contain elements. How do we retrieve the type when the list is empty?
Solution: Check attribute type
To solve this problem, we can check pi.PropertyType itself. If it's a generic type whose definition matches List
Modified code
<code class="language-csharp">Type type = pi.PropertyType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { Type itemType = type.GetGenericArguments()[0]; // 这将给出类型 }</code>
Handling non-List interfaces
For more general support for various types implementing IList
<code class="language-csharp">foreach (Type interfaceType in type.GetInterfaces()) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList<>)) { Type itemType = interfaceType.GetGenericArguments()[0]; // 注意此处使用 interfaceType // 对项目类型执行某些操作... } }</code>
This revised answer improves clarity and corrects a minor error in the final code snippet. The type parameter should be extracted from interfaceType
not type
in the IList<>
example. The use of List<>
instead of List
in the generic type definition check is also more accurate.
The above is the detailed content of How to Determine the Type Parameter of an Empty Generic List in C#?. For more information, please follow other related articles on the PHP Chinese website!