在事件(字段定义事件)上使用属性时,有三种可能的属性目标,即事件,字段和方法。我理解事件和字段目标的用法,但方法目标在哪里适用。
例如
[AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=true)]
internal class TestAttribute : Attribute
{
}
internal class Test
{
[event: Test]
[field: Test]
[method: Test]
public event Action action;
}
答案 0 :(得分:1)
据我所知,它适用于编译器生成的“add”和“remove”方法(执行订阅/取消订阅的方法):
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));
}
}