Usage of targets on events using attributes

2019-07-17 17:32发布

There are three possible attribute targets when using attributes on events (field defined events) and those are event, field and method. I understand the usage of event and field target, but where does the method target apply.

for example

[AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=true)]
internal class TestAttribute : Attribute
{
}
internal class Test
{
    [event: Test]
    [field: Test]
    [method: Test]
    public event Action action;
}

1条回答
beautiful°
2楼-- · 2019-07-17 18:01

As far as I can tell, it's applied to the "add" and "remove" methods generated by the compiler (the methods which perform the subscription/unsubscription):

using System;
using System.Reflection;
using System.Runtime.CompilerServices;

[AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=true)]
internal class TestAttribute : Attribute
{
}
internal class Test
{
    [event: Test]
    [field: Test]
    [method: Test]
    public event Action action;

    static void Main() 
    {
        MethodInfo method = typeof(Test).GetEvent("action")
                                        .GetRemoveMethod(); // Or GetAddMethod
        Console.WriteLine(method.IsDefined(typeof(TestAttribute), true));
    }
}
查看更多
登录 后发表回答