簡體   English   中英

檢查 PropertyDescriptor 是否有屬性

[英]check if PropertyDescriptor has attribute

我正在嘗試檢查屬性是否應用了 DataMemberAttribute(使用 TypeDescriptor)

這就是我現在所擁有的:

PropertyDescriptor targetProp = targetProps[i];

var has = argetProp.Attributes.Contains(
Attribute.GetCustomAttribute(typeof(DataMemberAttribute).Assembly,typeof(DataMemberAttribute)));

問題是

Attribute.GetCustomAttribute(typeof(DataMemberAttribute).Assembly,typeof(DataMemberAttribute))

返回空值

你可以使用 LINQ。 .OfType<T>().OfType<T>() .Any()擴展方法鏈可以很好地完成這項工作:

PropertyDescriptor targetProp = targetProps[i];
bool hasDataMember = targetProp.Attributes.OfType<DataMemberAttribute>().Any();

在那里找到了一個更好的答案: https : //stackoverflow.com/a/2051116/605586

基本上你可以使用:

bool hasDataMember = Attribute.IsDefined(property, typeof(DataMemberAttribute));

有3種方式:

  • 第一的:

     PropertyDescriptor targetProp = targetProps[i]; bool hasDataMember = targetProp.Attributes.Contains(new DataMemberAttribute());
  • 第二:

     PropertyDescriptor targetProp = targetProps[i]; bool hasDataMember = targetProp.Attributes.OfType<DataMemberAttribute>().Any();
  • 第三:

     PropertyDescriptor targetProp = targetProps[i]; bool hasDataMember = targetProp.Attributes.Matches(new DataMemberAttribute());

最良好的問候!

暫無
暫無

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

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