问题
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