简体   繁体   中英

Custom Attribute reflection on property

I have this basic class with one custom Attribute

public class Foo
{
    [MyAttribute]
    public DateTime CurrentDate {get;set;}
}

I'm using reflection to see if CurrentDate has a MyAttribute on it.

I create a new instance of Foo :

var foo = new Foo();

I reflect on foo :

foo.GetType().GetProperty("CurrentDate").GetCustomAttributes(true);

this gives me my custom attributes.

However, if I reflect like this:

foo.CurrentDate.GetType().GetCustomAttributes(true);

it returns what seems to be native attributes and mine is not in there.

So my question is, why is it doing that?

foo.CurrentDate.GetType() will return typeof(DateTime) . That's because foo.CurrentDate is declared as a DateTime . GetType() returns information about the type of the value you give it, not information about the property that the value came from.

Do you mean to do something like foo.GetType().GetProperty(nameof(foo.CurrentDate)).GetCustomAttributes() ?

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