繁体   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