C# Extension method for checking attributes

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

    I don't think you'll be able to implement that exactly as you described. The MethodName(params) part of your statement will actually execute the method, returning whatever the method returns, and not information about the method.

    What you want to do is pass in a MethodInfo into your extension class, using reflection. So instead of your example, you'd probably end up with something like:

     controller.GetType().GetMethod(methodName).HasAttribute();
    

    You could probably simplify this down to a single extension method on the controller class by encapsulating GetType().GetMethod(), like so:

     controller.MethodHasAttribute(methodName, attributeName);
    

提交回复
热议问题