[英]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.