简体   繁体   English

检查 PropertyDescriptor 是否有属性

[英]check if PropertyDescriptor has attribute

I'm trying to check if a property has the DataMemberAttribute applied (using TypeDescriptor)我正在尝试检查属性是否应用了 DataMemberAttribute(使用 TypeDescriptor)

this is what I have now:这就是我现在所拥有的:

PropertyDescriptor targetProp = targetProps[i];

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

the problem is that问题是

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

returns null返回空值

You could use LINQ.你可以使用 LINQ。 A chain of the .OfType<T>() and .Any() extension methods would do the job just fine: .OfType<T>().OfType<T>() .Any()扩展方法链可以很好地完成这项工作:

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

Found a much nicer answer in there: https://stackoverflow.com/a/2051116/605586在那里找到了一个更好的答案: https : //stackoverflow.com/a/2051116/605586

Basically you can just use:基本上你可以使用:

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

There are 3 ways:有3种方式:

  • First:第一的:

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

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

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

Best Regard!最良好的问候!

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

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