简体   繁体   中英

How do I reflect custom attributes on a reference property without getting ones attached to the class?

Lets say I have:

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

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

When I reflect on PropertyA, I see the attributes of class A. Why?

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

prints out:

System.ComponentModel.DescriptionAttribute

Why is the DescriptionAttribute in the list when i reflect on the property? How do I exclude class attributes and just get ones attached to the property?

Change:

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

to:

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

The documentation for the GetCustomAttributes() method is here: http://msdn.microsoft.com/en-us/library/dzdb2077(v=vs.100).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM