如何在运行时读取类的属性?

我正在尝试创建一个通用方法,该方法将读取类的属性并在运行时返回该值。我该怎么做?


注意:DomainName属性属于DomainNameAttribute类。


[DomainName("MyTable")]

Public class MyClass : DomainBase

{}

我想要生成的内容:


//This should return "MyTable"

String DomainNameValue = GetDomainName<MyClass>();


紫衣仙女
浏览 462回答 3
3回答

慕容森

已经有一个扩展来做到这一点。namespace System.Reflection{&nbsp; &nbsp; // Summary:&nbsp; &nbsp; //&nbsp; &nbsp; &nbsp;Contains static methods for retrieving custom attributes.&nbsp; &nbsp; public static class CustomAttributeExtensions&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute;&nbsp; &nbsp; }}所以:var attr = typeof(MyClass).GetCustomAttribute<DomainNameAttribute>(false);return attr != null ? attr.DomainName : "";

MM们

System.Reflection.MemberInfo info = typeof(MyClass);object[] attributes = info.GetCustomAttributes(true);for (int i = 0; i < attributes.Length; i++){&nbsp; &nbsp; if (attributes[i] is DomainNameAttribute)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.Console.WriteLine(((DomainNameAttribute) attributes[i]).Name);&nbsp; &nbsp; }&nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP