Mit folgenden Extension-Methoden können Attribute eines Members abgerufen werden.
public static A GetAttribute<A>(this MemberInfo memberInfo, Boolean inherit)
where A : Attribute
{
object[] attributes;
if ((attributes = memberInfo.GetCustomAttributes(typeof(A), inherit)).Length > 0)
return (A) attributes[0];
return default(A);
}
public static A[] GetAttributes<A>(this MemberInfo memberInfo, Boolean inherit)
where A : Attribute
{
object[] attributes;
if ((attributes = memberInfo.GetCustomAttributes(typeof(A), inherit)).Length > 0)
return (from a in attributes select (A) a).ToArray();
return null;
}
So wird die GetAttribute-Methode verwendet…
class Class1
{
[System.Xml.Serialization.XmlElement("property1")]
public string Property1 { get; set; }
}
...
using System.Reflection;
using System.Xml.Serialization;
...
PropertyInfo p = typeof(Class1).GetProperty("Property1");
XmlElementAttribute a = p.GetAttribute<XmlElementAttribute>(false);
...
