美好的一天,如果我擁有該屬性的自定義屬性值,我該如何獲取類的屬性名稱?當然還有自定義屬性名稱。按屬性值獲取屬性名稱
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. 如何從類實例的屬性中獲取屬性名稱?
請解釋更多,你的問題現在並不十分清楚,並且可能會被關閉。 –