How to check if method has an attribute

后端 未结 5 1560
礼貌的吻别
礼貌的吻别 2020-12-15 16:32

I have an example class

public class MyClass{

    ActionResult Method1(){
        ....
    } 

    [Authorize]
    ActionResult Method2(){
       ....
    }         


        
5条回答
  •  余生分开走
    2020-12-15 17:09

    There is a easier solution availabe compared to the others above with the current .NET/C# version (4.6.1, C#6):

    If you only have one one method with that name:

    var method = typeof(TestClass).GetMethods()
      .SingleOrDefault(x => x.Name == nameof(TestClass.TestMethod));
    
    var attribute = method?.GetCustomAttributes(typeof(MethodAttribute), true)
      .Single() as MethodAttribute;
    

    Now to check if you have the attribute set on the method:

    bool isDefined = attribute != null;
    

    And if you want to access the properties of the attribute, you can do this easy as that:

    var someInfo = attribute.SomeMethodInfo
    

    If there are multiple methods with the same name, you can go on and use method.GetParameters() and check for the parameters, instead of .GetMethods().Single...

    If you know that your method has no parameters, this check is easy:

    var method = typeof(TestClass).GetMethods()
        .SingleOrDefault(
          x => x.Name == nameof(TestClass.TestMethod) 
          && x.GetParameters().Length == 0
    );
    

    If not, this is going to be more complicated (checking parameters, etc.) and the other solutions are way easier and robust to use.

    So: Use this if you have no overloads for a method, or only want to read attributes from a method with a specified amount of parameters. Else, use the MethodOf provided by other answers in here.

提交回复
热议问题