Attribute GetCustomAttribute via method info of type

FredGrit發表於2024-03-09
[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}");
            }
        }
    }
}

  

相關文章