我想知道我的textBox1变量是否具有ABCAttribute。我该如何检查?

最佳答案

您需要存在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;
}

关于c# - (.net)如何检查给定变量是否使用属性定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1140719/

10-12 19:19