美好的一天,如果我拥有该属性的自定义属性值,我该如何获取类的属性名称?当然还有自定义属性名称。按属性值获取属性名称
2
A
回答
0
通过自定义属性获取属性名称:
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();
}
}
测试夹具:
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;
}
}
}
测试用例:
// 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"
);
相关问题
- 1. C#按属性名称获取Xelement属性值
- 2. .NET:获取属性名称属性
- 3. 按名称获取ActiveRecord的属性
- 4. 按属性名称获取HTML元素
- 5. AutoMapperMappingException获取属性名称
- 6. 未获取名称属性
- 7. 获取属性名称
- 8. 获取属性名称
- 9. 按属性名称
- 10. 获取属性名称的默认值
- 11. Java获取名称属性的值
- 12. 获取属性名称值<input>
- 13. 获取值来自的属性名称
- 14. 从ElementTree获取属性名称和值
- 15. 通过从XML传递属性名称获取属性值
- 16. 获取属性名称除了xml中的属性值
- 17. 按名称排序属性
- 18. 按名称检索属性
- 19. php - 获取单选按钮名称属性值
- 20. XSLT:按属性名称获取元素的值
- 21. 按名称设置属性值
- 22. 获取属性名
- 23. 转换对象的属性名称的属性和属性值
- 24. 获取方法名称,其中属性被访问并读取属性值
- 25. 如何从属性集中获取属性名称列表
- 26. 从数组属性的表达式获取属性名称
- 27. 如何从该属性的getter/setter中获取属性名称?
- 28. 如何获取属性设置的属性名称?
- 29. 如何获取自定义属性的属性类型名称?
- 30. 如何从类实例的属性中获取属性名称?
请解释更多,你的问题现在并不十分清楚,并且可能会被关闭。 –