
C# 中如何确定泛型 List 的类型参数
在使用反射和操作集合时,确定泛型 List 的类型参数至关重要。如果属性为空,获取类型可能是一个挑战。
存在问题的原始代码
考虑以下代码:
1 2 3 4 5 6 7 8 9 10 | foreach (PropertyInfo pi in lbxObjects.SelectedItem. GetType ().GetProperties())
{
switch (pi.PropertyType.Name.ToLower())
{
case "list`1" :
Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));
}
}
|
登录后复制
在此代码中,GetGenericType 方法用于获取类型参数,但它需要列表包含元素。当列表为空时,我们如何检索类型?
解决方案:检查属性类型
为了解决这个问题,我们可以检查 pi.PropertyType 本身。如果它是一个泛型类型,其定义与 List 匹配,我们可以使用 GetGenericArguments() 来提取类型参数。
修改后的代码
1 2 3 4 5 | Type type = pi.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
Type itemType = type.GetGenericArguments()[0];
}
|
登录后复制
处理非 List 接口
为了更普遍地支持实现 IList 的各种类型,可以使用 GetInterfaces() 检查接口:
1 2 3 4 5 6 7 8 | foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList<>))
{
Type itemType = interfaceType.GetGenericArguments()[0];
}
}
|
登录后复制
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.
以上是如何在 C# 中确定空泛型列表的类型参数?的详细内容。更多信息请关注PHP中文网其他相关文章!