c# - 通过反射获取 MemberInfo 的类型

标签 c# .net reflection attributes custom-attributes

我正在使用反射加载具有项目类结构的 TreeView 。类中的每个成员都分配有自定义属性。

我在使用 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 实例的目标类型,以便我可以适本地处理它?我觉得我遗漏了一些明显的东西,但我现在正在原地打转。

最佳答案

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

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...
    }
}

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

关于c# - 通过反射获取 MemberInfo 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15921608/

相关文章:

java - 使用 Java 反射创建静态抽象类的实例?

c# - 故意编写易受命令注入(inject)攻击的页面

c# - 在 SSL 包装器的本地用户连接之后或之前建立远程 SSL 连接?

c# - C# 中的 Luatable 等价物?

.net - 我需要编写什么代码来生成此代码?

java - 如何将DTO解析为Pojo对象

c# - Silverlight 中匿名类型的属性反射失败

c# - MEF 进口最小起订量?

.net - C#通过asp.net传输大文件到远程服务器的多种方式

.net - 如何检测加载图像是否会在 .NET 中引发 OutOfMemory 异常?