【问题标题】:How do I reflect custom attributes on a reference property without getting ones attached to the class?如何在不将自定义属性附加到类的情况下在参考属性上反映自定义属性?
【发布时间】:2013-05-24 15:51:37
【问题描述】:

假设我有:

[Description("Class Description")]
public class A { }

public class B { 
    public A PropertyA { get;set;}
}

当我反思PropertyA时,我看到了A类的属性。为什么?

var entityProperties = TypeDescriptor.GetProperties(typeof(B)).Cast<PropertyDescriptor>();
foreach (var a in entityProperties.First().Attributes)
    Console.Out.Write(a.GetType().ToString());

打印出来:

System.ComponentModel.DescriptionAttribute

为什么当我反映属性时,DescriptionAttribute 在列表中?如何排除类属性并仅获取附加到属性的属性?

【问题讨论】:

    标签: c# .net reflection custom-attributes


    【解决方案1】:

    变化:

    foreach (var a in entityProperties.First().Attributes)
    

    到:

    foreach (var a in entityProperties.First().GetCustomAttributes(true))
    

    GetCustomAttributes() 方法的文档在这里:http://msdn.microsoft.com/en-us/library/dzdb2077(v=vs.100).aspx

    【讨论】:

    • PropertyDescriptor 似乎没有 GetCustomAttributes()。但是,PropertyInfo 可以。如果我切换代码以获取 PropertyInfos,它似乎工作得更好.. 但是为什么呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多