本文介绍了获得一个的MemberInfo与反射型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

I'm using reflection to load a treeview with the class structure of a project. Each of the members in a class have a custom attribute assigned to them.

我没有一个问题得到的属性一类使用 MemberInfo.GetCustomAttributes()不过,我需要制定的一种方式,如果一个类成员是一个自定义类,然后需要分析自身返回自定义属性。

I don't have a problem getting the attributes for a class using MemberInfo.GetCustomAttributes() however I need a way of working out if a class member is a custom class and then needs parsing itself to return the custom attributes.

到目前为止,我的code是:

So far, my code is:

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实例,这样就可以适当地处理它的目标类型的一个简单的方法?我觉得我失去了一些东西很明显,但我在圈子在一分钟兜兜。

Is there an easy way of getting the target type of a MemberInfo instance so I can handle it appropriately? I feel I'm missing something obvious but I'm going round in circles at the minute.

推荐答案

的GetProperties,返回的PropertyInfo数组等等您应该使用。
然后,它仅仅是使用<$c$c>PropertyType属性。

GetProperties returns an array of PropertyInfo so you should use that.
Then it is simply a matter of using the PropertyType property.

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

foreach (PropertyInfo propertyInfo in propertyInfos)
{
    // ...
    if(propertyInfo.PropertyType == typeof(MyCustomClass))
        // ...
}

这篇关于获得一个的MemberInfo与反射型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 13:03