美好的一天,如果我擁有該屬性的自定義屬性值,我該如何獲取類的屬性名稱?當然還有自定義屬性名稱。按屬性值獲取屬性名稱
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. .NET:獲取屬性名稱屬性
- 2. 按屬性名稱獲取HTML元素
- 3. 按名稱獲取ActiveRecord的屬性
- 4. AutoMapperMappingException獲取屬性名稱
- 5. 獲取屬性名稱
- 6. 獲取屬性名稱
- 7. 按屬性名稱
- 8. 獲取屬性名稱的默認值
- 9. 獲取值來自的屬性名稱
- 10. 獲取屬性名稱值<input>
- 11. Java獲取名稱屬性的值
- 12. 獲取屬性名稱除了xml中的屬性值
- 13. 按名稱排序屬性
- 14. 按名稱檢索屬性
- 15. 轉換對象的屬性名稱的屬性和屬性值
- 16. 獲取方法名稱,其中屬性被訪問並讀取屬性值
- 17. 從多個屬性標記中提取屬性名稱和值
- 18. 如何從屬性集中獲取屬性名稱列表
- 19. 如何獲取自定義屬性的屬性類型名稱?
- 20. 如何從該屬性的getter/setter中獲取屬性名稱?
- 21. 在聲明的屬性中獲取屬性名稱
- 22. 如何獲取屬性設置的屬性名稱?
- 23. @RequestParam,名稱與值屬性
- 24. 從屬性中獲取屬性值
- 25. 獲取特定屬性的屬性值
- 26. 從innerHTML獲取名稱屬性
- 27. 獲取ABPerson屬性的標籤名稱
- 28. 獲取C#中的屬性名稱
- 29. 通過名稱獲取屬性
- 30. 如何獲取表單名稱屬性
請解釋更多,你的問題現在並不十分清楚,並且可能會被關閉。 –