簡體   English   中英

屬性的自定義屬性反射

[英]Custom Attribute reflection on property

我有一個帶有一個自定義Attribute基本類

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

我正在使用反射來查看CurrentDate是否具有MyAttribute

我創建一個Foo的新實例:

var foo = new Foo();

我反思foo

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

這給了我我的自定義屬性。

但是,如果我這樣反映:

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

它返回似乎是本機屬性的內容,而我的屬性不在其中。

所以我的問題是,為什么要這樣做?

foo.CurrentDate.GetType()將返回typeof(DateTime) 這是因為foo.CurrentDate被聲明為DateTime GetType()返回有關您賦予它的值的類型的信息,而不是有關該值來自的屬性的信息。

您是否打算做類似foo.GetType().GetProperty(nameof(foo.CurrentDate)).GetCustomAttributes()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM