[英]Get property name by attribute value
Good day, How can I get class's property name, if I have custom attribute value for that property? 美好的一天,如果我有该类的自定义属性值,该如何获取类的属性名? and custom attribute name of course.
和自定义属性名称。
Get property name by custom attribute: 通过自定义属性获取属性名称:
public static string[] GetPropertyNameByCustomAttribute
<ClassToAnalyse, AttributeTypeToFind>
(
Func<AttributeTypeToFind, bool> attributePredicate
)
where AttributeTypeToFind : Attribute
{
if (attributePredicate == null)
{
throw new ArgumentNullException("attributePredicate");
}
else
{
List<string> propertyNames = new List<string>();
foreach
(
PropertyInfo propertyInfo in typeof(ClassToAnalyse).GetProperties()
)
{
if
(
propertyInfo.GetCustomAttributes
(
typeof(AttributeTypeToFind), true
).Any
(
currentAttribute =>
attributePredicate((AttributeTypeToFind)currentAttribute)
)
)
{
propertyNames.Add(propertyInfo.Name);
}
}
return propertyNames.ToArray();
}
}
Test fixtures: 测试治具:
public class FooAttribute : Attribute
{
public String Description { get; set; }
}
class FooClass
{
private int fooProperty = 42;
[Foo(Description="Foo attribute description")]
public int FooProperty
{
get
{
return this.fooProperty;
}
}
}
Test cases: 测试用例:
// It will return "FooProperty"
GetPropertyNameByCustomAttribute<FooClass, FooAttribute>
(
attribute => attribute.Description == "Foo attribute description"
);
// It will return an empty array
GetPropertyNameByCustomAttribute<FooClass, FooAttribute>
(
attribute => attribute.Description == "Bar attribute description"
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.