C# 获取枚举的自定义属性的属性
我的项目具有以下BookDetails属性:C# 获取枚举的自定义属性的属性,c#,reflection,attributes,custom-attributes,C#,Reflection,Attributes,Custom Attributes,我的项目具有以下BookDetails属性: public enum Books { [BookDetails("Jack London", 1906)] WhiteFange, [BookDetails("Herman Melville", 1851)] MobyDick, [BookDetails("Lynne Reid Banks", 1980)] IndianInTheCupboard } 属性的名称和代码如下: [Attribut
public enum Books
{
[BookDetails("Jack London", 1906)]
WhiteFange,
[BookDetails("Herman Melville", 1851)]
MobyDick,
[BookDetails("Lynne Reid Banks", 1980)]
IndianInTheCupboard
}
属性的名称和代码如下:
[AttributeUsage(AttributeTargets.Field)]
public class BookDetails : Attribute
{
public string Author { get; }
public int YearPublished { get; }
public BookDetails(string author, int yearPublished)
{
Author = author;
YearPublished = yearPublished;
}
}
我如何找到一本书的作者
尝试了此混乱的代码,但无效:
var author = Books.IndianInTheCupboard.GetType().GetCustomAttributes(false).GetType().GetProperty("Author"); // returns null
谢谢,肯定有比我上面尝试的更好的方法。由于属性附加到
enum
字段,您应该将GetCustomAttribute
应用到FieldInfo
:
var res = typeof(Books)
.GetField(nameof(Books.IndianInTheCupboard))
.GetCustomAttribute<BookDetails>(false)
.Author;
var res=typeof(书籍)
.GetField(书的名称,印在黑板上)
.GetCustomAttribute(false)
作者
由于属性类型是静态已知的,因此应用GetCustomAttribute
方法的泛型版本可以为获取Author
属性提供更好的类型安全性
已经由布莱恩·罗撰写。复制他的解决方案符合您的示例:
var type = typeof(Books);
var memInfo = type.GetMember(Books.IndianInTheCupboard.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(BookDetails), false);
var description = ((BookDetails)attributes[0]).Author;
您的解决方案不起作用,因为您正在尝试查找Books类型的属性,而不是枚举元素的属性。 它起作用了
var fieldInfo = typeof(Books).GetField(Books.IndianInTheCupboard.ToString());
var attribute = fieldInfo.GetCustomAttributes(typeof(BookDetails), false).FirstOrDefault() as BookDetails;
var author = attribute.Author;
如果需要经常获取该属性的值,可以为其编写扩展
public static class EnumExtensions
{
public static BookDetails GetDescription(this Books value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var attribute = fieldInfo.GetCustomAttributes(typeof(BookDetails), false).FirstOrDefault() as BookDetails;
return attribute;
}
}
喜欢扩展方法。