获取带有反射的MemberInfo的类型

本文关键字:类型 MemberInfo 反射的 获取 | 更新日期: 2023-09-27 18:08:38

我使用反射来加载带有项目类结构的树视图。类中的每个成员都有一个自定义属性。

我没有问题获得使用MemberInfo.GetCustomAttributes()类的属性,但是我需要一种方法来确定类成员是否为自定义类,然后需要解析自身以返回自定义属性。

目前为止,我的代码是:
MemberInfo[] membersInfo = typeof(Project).GetProperties();
foreach (MemberInfo memberInfo in membersInfo)
{
    foreach (object attribute in memberInfo.GetCustomAttributes(true))
    {
        // Get the custom attribute of the class and store on the treeview
        if (attribute is ReportAttribute)
        {
            if (((ReportAttribute)attribute).FriendlyName.Length > 0)
            {
               treeItem.Items.Add(new TreeViewItem() { Header = ((ReportAttribute)attribute).FriendlyName });
            }
        }
        // PROBLEM HERE : I need to work out if the object is a specific type
        //                and then use reflection to get the structure and attributes.
    }
}

是否有一种简单的方法来获得MemberInfo实例的目标类型,以便我可以适当地处理它?我觉得我错过了一些明显的东西,但我现在正在兜圈子。

获取带有反射的MemberInfo的类型

我认为如果你使用这个扩展方法,你可以获得更好的性能:

public static Type GetUnderlyingType(this MemberInfo member)
{
    switch (member.MemberType)
    {
        case MemberTypes.Event:
            return ((EventInfo)member).EventHandlerType;
        case MemberTypes.Field:
            return ((FieldInfo)member).FieldType;
        case MemberTypes.Method:
            return ((MethodInfo)member).ReturnType;
        case MemberTypes.Property:
            return ((PropertyInfo)member).PropertyType;
        default:
            throw new ArgumentException
            (
             "Input MemberInfo must be if type EventInfo, FieldInfo, MethodInfo, or PropertyInfo"
            );
    }
}

应该适用于任何MemberInfo,而不仅仅是PropertyInfo。您可以从该列表中避免MethodInfo,因为它本身不是底层类型(而是返回类型)。

在你的例子中:

foreach (MemberInfo memberInfo in membersInfo)
{
    foreach (object attribute in memberInfo.GetCustomAttributes(true))
    {
        if (attribute is ReportAttribute)
        {
            if (((ReportAttribute)attribute).FriendlyName.Length > 0)
            {
               treeItem.Items.Add(new TreeViewItem() { Header = ((ReportAttribute)attribute).FriendlyName });
            }
        }
        //if memberInfo.GetUnderlyingType() == specificType ? proceed...
    }
}

GetProperties返回一个PropertyInfo的数组,所以你应该使用它。
然后,只需使用PropertyType属性即可。

PropertyInfo[] propertyInfos = typeof(Project).GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
    // ...
    if(propertyInfo.PropertyType == typeof(MyCustomClass))
        // ...
}