简体   繁体   中英

(.net) How to check if a given variable is defined with an attribute

I'd like to know if my textBox1 variable has the ABCAttribute. How can I check this?

You need a handle to the class (type) in which textBox1 exists:

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

This is a bit nasty, one possibility is to roll it into an extension method, used like so:

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

Assuming textBox1 is, well, a TextBox control, then the answer is likely, "No, it doesn't have the attribute." Attributes are assigned to a Type , not an instance of the type. You can lookup what attributes are on any TextBox that ever was, is, or will be created right now (for a particular version of the framework).

Do you mean the attributes as in:

<input class="textbox" type="text" value="search" ABC="val" name="q"/> 

In that case you can look up the attribute name in the control's Attribute collection.

WebForm Textbox control Attributes collection

If you mean attributes as in:

<ValidationPropertyAttribute("Text")> _
<ControlValuePropertyAttribute("Text")> _
Public Class TextBox _ 
...

then as the other posters have mentioned, you will have to use Reflection to determine if the control has a particular attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM