C# Extension method for checking attributes

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

    Can't quite do exactly that with extension methods, but this is close:

    public static class Program
    {
      static void Main(string[] args)
      {
         Controller c1 = new Controller();
         Action a1 = c1.Method1;
         Console.WriteLine(a1.HasAttribute());
      }
    
      public static bool HasAttribute(this Action method)
      {
         return method.Method.GetCustomAttributes(typeof(T), false).Any();
      }
    }
    
    class Controller
    {
      [AttributeUsage(AttributeTargets.Method)]
      public class TestAttribute : System.Attribute
      {
      }
    
      [Test()]
      public void Method1()
      {
      }
    }
    

提交回复
热议问题