首页 > 后端开发 > C++ > 如何在 C# 中确定空泛型列表的类型参数?

如何在 C# 中确定空泛型列表的类型参数?

Susan Sarandon
发布: 2025-01-08 19:06:46
原创
1095 人浏览过

How to Determine the Type Parameter of an Empty Generic List in C#?

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":

            // 如果 List<T> 包含元素,则此方法有效。

            Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));

            // 但如果值为 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]; // 注意此处使用 interfaceType

        // 对项目类型执行某些操作...

    }

}

登录后复制

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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板