(.net)如何检查给定变量是否使用属性定义

dev*_*ium 1 .net c# vb.net attributes

我想知道我的textBox1变量是否具有ABCAttribute.我怎么检查这个?

Rex*_*x M 6

您需要一个textBox1所在的类(类型)的句柄:

Type myClassType = typeof(MyClass);

MemberInfo[] members = myClassType.GetMember("textBox1",
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

if(members.Length > 0) //found a member called "textBox1"
{
    object[] attribs = members[0].GetCustomAttributes(typeof(ABCAttribute));

    if(attribs.Length > 0) //found an attribute of type ABCAttribute
    {
        ABCAttribute myAttrib = attribs[0] as ABCAttribute;
        //we know "textBox1" has an ABCAttribute,
        //and we have a handle to the attribute!
    }
}
Run Code Online (Sandbox Code Playgroud)

这有点讨厌,一种可能性就是把它变成一个扩展方法,就像这样使用:

MyObject obj = new MyObject();
bool hasIt = obj.HasAttribute("textBox1", typeof(ABCAttribute));

public static bool HasAttribute(this object item, string memberName, Type attribute)
{
    MemberInfo[] members = item.GetType().GetMember(memberName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    if(members.Length > 0)
    {
        object[] attribs = members[0].GetCustomAttributes(attribute);
        if(attribs.length > 0)
        {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)