查找具有自定义属性的属性-MyAttribute
var props = t.GetProperties(BindingFlags.NonPublic |BindingFlags.Public| BindingFlags.Instance).Where( prop => Attribute.IsDefined(prop, typeof(MyAttribute)));
查找给定属性上的所有自定义属性
var attributes = typeof(t).GetProperty("Name").GetCustomAttributes(false);枚举具有自定义属性的所有类-MyAttribute
static IEnumerable<Type> GetTypesWithAttribute(Assembly assembly) {
foreach(Type type in assembly.GetTypes()) {
if (type.GetCustomAttributes(typeof(MyAttribute), true).Length > 0) {
yield return type;
}
}
}在运行时读取自定义属性的值
public static class AttributeExtensions
{
/// <summary>
///返回类中任何成员的成员属性值。
///(成员是字段,属性,方法等)
/// <remarks>
///如果类中有多个同名成员,则它将返回第一个(这适用于重载方法)
/// </remarks>
/// <example>
/// ReadSystem.ComponentModelDescription属性,来自类“ MyClass”中的方法“ MyMethodName”:
/// var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) => d.Description);
/// </example>
/// <param name="type">The class that contains the member as a type</param>
/// <param name="MemberName">Name of the member in the class</param>
/// <param name="valueSelector">Attribute type and property to get (will return first instance if there are multiple attributes of the same type)</param>
/// <param name="inherit">true to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events</param>
/// </summary>
public static TValue GetAttribute<TAttribute, TValue>(this Type type, string MemberName, Func<TAttribute, TValue> valueSelector, bool inherit = false) where TAttribute : Attribute
{
var att = type.GetMember(MemberName).FirstOrDefault().GetCustomAttributes(typeof(TAttribute), inherit).FirstOrDefault() as TAttribute;
if (att != null)
{
return valueSelector(att);
}
return default(TValue);
}
}用法
//类'MyClass'中方法'MyMethodName'的ReadSystem.ComponentModelDescription属性
var Attribute = typeof(MyClass).GetAttribute("MyMethodName", (DescriptionAttribute d) => d.Description);