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

时间:2009-07-16 22:48:00

标签: c# .net vb.net attributes

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

3 个答案:

答案 0 :(得分: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!
    }
}

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

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

答案 1 :(得分:2)

假设textBox1是一个TextBox控件,那么答案可能是“不,它没有属性”。属性分配给 Type ,而不是类型的实例。您可以查找任何TextBox上的属性,这些属性现在是,现在或将要创建(对于特定版本的框架)。

答案 2 :(得分:0)

你的意思是如下的属性:

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

在这种情况下,您可以在控件的Attribute集合中查找属性名称。

WebForm Textbox control Attributes collection

如果您的意思是属性:

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

然后正如其他海报所提到的,你将不得不使用Reflection来确定控件是否具有特定属性。