简体   繁体   English

属性的自定义属性反射

[英]Custom Attribute reflection on property

I have this basic class with one custom Attribute 我有一个带有一个自定义Attribute基本类

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

I'm using reflection to see if CurrentDate has a MyAttribute on it. 我正在使用反射来查看CurrentDate是否具有MyAttribute

I create a new instance of Foo : 我创建一个Foo的新实例:

var foo = new Foo();

I reflect on foo : 我反思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) . foo.CurrentDate.GetType()将返回typeof(DateTime) That's because foo.CurrentDate is declared as a DateTime . 这是因为foo.CurrentDate被声明为DateTime GetType() returns information about the type of the value you give it, not information about the property that the value came from. GetType()返回有关您赋予它的值的类型的信息,而不是有关该值来自的属性的信息。

Do you mean to do something like foo.GetType().GetProperty(nameof(foo.CurrentDate)).GetCustomAttributes() ? 您是否打算做类似foo.GetType().GetProperty(nameof(foo.CurrentDate)).GetCustomAttributes()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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