c# - 使用属性在事件上使用目标

标签 c# events reflection custom-attributes

在事件(字段定义的事件)上使用属性时,存在三种可能的属性目标,它们是事件、字段和方法。我了解事件和字段目标的用法,但是方法目标适用于何处。

例如

[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/

相关文章:

c# - Linq Lambda - 浏览次数最多的页面

c# - 为什么此绑定(bind)不能通过 XAML 工作,而是通过代码工作?

php - 我如何将其绑定(bind)到 JQUERY 中的 onclick 事件?

Javascript 添加带有自定义回调的事件监听器?

接口(interface)中的 C# 事件 - 来自 vb.net 程序员的混淆

C#和反射的使用

c# - 在不使用 Thread.Sleep 的情况下大约每分钟运行一次任务

c#接收即插即用事件

java - 使用反射和 ClassLoaders 创建类的实例时出现 ClassCastException

c# - SOS.dll ObjSize 和 DumpObject 背后的复杂之处。如何在 C# 中重新创建 SOS.dll?