的屬性本身不會知道的它附加的類。您將需要使用其他服務/幫助器功能/無論將它們配對。
但是,您可能會發現下面的有用:
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