的属性本身不会知道的它附加的类。您将需要使用其他服务/帮助器功能/无论将它们配对。
但是,您可能会发现下面的有用:
public static bool HasAttribute<T, TAttribute>() where TAttribute : Attribute
{
return typeof (T).GetCustomAttributes(typeof (TAttribute), true).Any();
}
编辑:有关成员字段找到属性
/// <summary>
/// Returns all the (accessible) fields or properties that for a given type that
/// have the "T" attribute declared on them.
/// </summary>
/// <param name="type">Type object to search</param>
/// <returns>List of matching members</returns>
public static List<MemberInfo> FindMembers<T>(Type type) where T : Attribute
{
return FindMembers<T>(type, MemberTypes.Field | MemberTypes.Property);
}
/// <summary>
/// Returns all the (accessible) fields or properties that for a given type that
/// have the "T" attribute declared on them.
/// </summary>
/// <param name="type">Type object to search</param>
/// <returns>List of matching members</returns>
public static List<MemberInfo> FindMembers<T>(Type type, MemberTypes memberTypesFlags) where T : Attribute
{
const BindingFlags FieldBindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
List<MemberInfo> members = new List<MemberInfo>();
members.AddRange(type.FindMembers(
memberTypesFlags,
FieldBindingFlags,
HasAttribute<T>, // Use delegate from below...
null)); // This arg is ignored by the delegate anyway...
return members;
}
public static bool HasAttribute<T>(MemberInfo mi) where T : Attribute
{
return GetAttribute<T>(mi) != null;
}
public static bool HasAttribute<T>(MemberInfo mi, object o) where T : Attribute
{
return GetAttribute<T>(mi) != null;
}
但我不能在属性 – Tekno
中使用这个,你可以把它作为一个静态函数,但如果我是你,我会用它作为扩展方法或在一个静态辅助类中。 – Reddog
非常感谢!但我怎么能知道该属性绑定在属性本身内部的类来应用此!! !! !!?!例如,我有一个“OrderableAttribute”和一个“DefaultOrderAttribute”。如果我用“OrderableAttribute”定义一个类,我需要检查DefaultOrderAttribute是否也设置了 – Tekno