C# Extension method for checking attributes

后端 未结 6 1399
南笙
南笙 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:26

    Usage:

    bool hasAttribute = controller.HasMethodAttribute( "Test" )
    

    Extension:

    public static bool HasMethodAttribute( this object obj, string methodName )
    {
        Type type = obj.GetType();
    
        MethodInfo method = type.GetMethod( methodName );
        if( method == null )
        {
            throw new ArgumentException( string.Format( 
                "Method '{0}' not found on object '{1}'", methodName, type.Name ) );
        }
    
        return method.GetCustomAttributes( typeof( TAttribute ), true ).Length > 0 ;
    } 
    

提交回复
热议问题