tragets对使用属性事件用法 [英] Usage of tragets on events using attributes
本文介绍了tragets对使用属性事件用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在事件(字段定义的事件)上使用属性时,有三种可能的属性目标,即事件,字段和方法。我理解事件和字段目标的使用,但方法目标适用于哪里。
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.
例如
[AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=true)]
internal class TestAttribute : Attribute
{
}
internal class Test
{
[event: Test]
[field: Test]
[method: Test]
public event Action action;
}
推荐答案
,它适用于编译器生成的添加和删除方法(执行订阅/取消订阅的方法):
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));
}
}
这篇关于tragets对使用属性事件用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文