Attribute GetCustomAttribute via method info of type
[AttributeUsage(AttributeTargets.Method)] public sealed class TestAttribute:Attribute { public int Repetitions; public string FailureMessage; public TestAttribute():this(1) { } public TestAttribute(int repetitions) { Repetitions = repetitions; } } class Foo { [TestAttribute] public void Method1() { Console.WriteLine("Foo.Method1()"); } [Test(20)] public void Method2() { Console.WriteLine("Foo.Method2()"); } [Test(20,FailureMessage ="Debugging Time!")] public void Method3() { Console.WriteLine("Foo.Method3()"); } } internal class Program { static void Main(string[] args) { GetCustomAttrs(); LogInfo(); } static void GetCustomAttrs() { var mis = typeof(Foo).GetMethods(); foreach (var mi in mis) { TestAttribute att = (TestAttribute)Attribute.GetCustomAttribute(mi, typeof(TestAttribute)); if (att != null) { Console.WriteLine($"Method:{mi.Name} will be tested,reps={att.Repetitions},msg={att.FailureMessage}"); } } } }
static void Main(string[] args) { MethodInfoInvokeGetCustomAttributes(); LogInfo(); } static void MethodInfoInvokeGetCustomAttributes() { var mis = typeof(Foo).GetMethods(); foreach(var mi in mis) { Console.WriteLine(mi.Name); TestAttribute att=(TestAttribute)Attribute.GetCustomAttribute(mi, typeof(TestAttribute)); if(att != null) { for(int i=0;i<att.Repetitions;i++) { try { mi.Invoke(new Foo(), null); } catch (Exception ex) { throw new Exception("Error:" + att.FailureMessage, ex); } } Console.WriteLine("\n"); } } }