在事件(字段定义的事件)上使用属性时,存在三种可能的属性目标,它们是事件、字段和方法。我了解事件和字段目标的用法,但是方法目标适用于何处。
例如
[AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=true)]
internal class TestAttribute : Attribute
{
}
internal class Test
{
[event: Test]
[field: Test]
[method: Test]
public event Action action;
}
最佳答案
据我所知,它应用于编译器生成的“添加”和“删除”方法(执行订阅/取消订阅的方法):
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));
}
}
关于c# - 使用属性在事件上使用目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5482522/