C# Extension method for checking attributes

后端 未结 6 1410
南笙
南笙 2021-02-02 17:44

Sorry if this is a stupid noob question please be gentle with me I\'m trying to learn...

I want to test against the attribute methods of things like models and controlle

6条回答
  •  故里飘歌
    2021-02-02 18:22

    Perhaps you are looking for this:

    Controller controller = new Controller();
    bool ok = controller.GetMethod(c => c.MethodName(null, null))
        .HasAttribute();
    

    What's nice about writing it like this is that you have fully compile time support. All other solutions thus far use string literals to define the methods.

    Here are the implementations of the GetMethod and HasAttribute extension methods:

    public static MethodInfo GetMethod(this T instance,
        Expression> methodSelector)
    {
        // Note: this is a bit simplistic implementation. It will
        // not work for all expressions.
        return ((MethodCallExpression)methodSelector.Body).Method;
    }
    
    public static MethodInfo GetMethod(this T instance,
        Expression> methodSelector)
    {
        return ((MethodCallExpression)methodSelector.Body).Method;
    }
    
    public static bool HasAttribute(
        this MemberInfo member) 
        where TAttribute : Attribute
    {
        return GetAttributes(member).Length > 0;
    }
    
    public static TAttribute[] GetAttributes(
        this MemberInfo member) 
        where TAttribute : Attribute
    {
        var attributes = 
            member.GetCustomAttributes(typeof(TAttribute), true);
    
        return (TAttribute[])attributes;
    }
    

提交回复
热议问题