gpt4 book ai didi

c# - 属性和类

转载 作者:行者123 更新时间:2023-11-30 22:34:51 26 4
gpt4 key购买 nike

我正在搜索如何在属性定义中知道我应用该属性的类是否具有另一个属性
示例:

[My1Attribute]  
public class MyClass
{
[My2Attribute]
int aux{get;set;}

}

internal sealed class My1Attribute : Attribute
{
public My1Attribute
{
// How can I Know if 'MyClass' has My2Attribute applied ???
}
}

最佳答案

属性本身不知道它所附加的类。您将需要使用其他一些服务/辅助功能/任何东西来配对它们。

但是,您可能会发现以下内容很有用:

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;
}

关于c# - 属性和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7652334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com