Usage of targets on events using attributes

依然范特西╮ 提交于 2019-12-24 00:34:01

问题


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:


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));
    }
}


来源:https://stackoverflow.com/questions/5482522/usage-of-targets-on-events-using-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!