使用反射获取MemberInfo的类型

Gra*_*ush 24 .net c# reflection attributes custom-attributes

我正在使用反射来加载具有项目类结构的树视图.类中的每个成员都具有分配给它们的自定义属性.

获取类的属性我没有问题,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.
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来获取MemberInfo实例的目标类型,以便我可以适当地处理它?我觉得我错过了一些显而易见的东西,但我现在正在转圈.

naw*_*fal 55

我认为如果你随身携带这种扩展方法,你可以获得更好的性能:

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"
            );
    }
}
Run Code Online (Sandbox Code Playgroud)

应该为任何工作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...
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道为什么默认情况下这不是BCL的一部分.


Dan*_*rth 10

GetProperties返回一个数组,PropertyInfo所以你应该使用它.
然后,这只是使用该PropertyType属性的问题.

PropertyInfo[] propertyInfos = typeof(Project).GetProperties();

foreach (PropertyInfo propertyInfo in propertyInfos)
{
    // ...
    if(propertyInfo.PropertyType == typeof(MyCustomClass))
        // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,`MemberInfo [] membersInfo =`是一个坏兆头.我喜欢`var`的原因之一 - 减少出错的事情. (5认同)