【发布时间】:2012-03-24 10:37:24
【问题描述】:
C# 允许我们to create custom event accessors。
Action _custom;
public event Action Custom
{
add { _custom = (Action)Delegate.Combine( _custom, value ); }
remove { _custom = (Action)Delegate.Remove( _custom, value ); }
}
如果您不指定它们,the compiler creates them for you。 C# 语言规范:
在编译类字段事件时,编译器会自动创建 存储来保存委托,并为事件创建访问器 向委托字段添加或删除事件处理程序。
使用dotPeek 对简单的public event Action Public; 进行反编译的源代码如下所示:
private Action Public;
public event Action Public
{
add
{
Action action = this.Public;
Action comparand;
do
{
comparand = action;
action = Interlocked.CompareExchange<Action>(
ref this.Public, comparand + value, comparand);
}
while (action != comparand);
}
remove
{
Action action = this.Public;
Action comparand;
do
{
comparand = action;
action = Interlocked.CompareExchange<Action>(
ref this.Public, comparand - value, comparand);
}
while (action != comparand);
}
}
值得注意的是字段和事件使用相同的名称。这导致some people 得出结论,您可以通过在类中查找与事件同名的字段来在反射期间找到有关支持字段的信息。我是这样实现的:
public static FieldInfo GetFieldInfo( this EventInfo eventInfo )
{
Contract.Requires( eventInfo != null );
return eventInfo.DeclaringType.GetField(
eventInfo.Name,
BindingFlags.DeclaredOnly | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic );
}
这可行,但提出了一个问题:编译器生成的事件的支持字段是否总是保证使用与事件相同的名称?
无法使用 Visual Studio 创建访问同名委托的自定义事件访问器。这会导致消息:“已声明同名的成员。”我想知道您是否可以得出结论,任何没有同名支持委托可用的事件都是自定义事件访问器。
【问题讨论】:
标签: c# events reflection compiler-construction delegates