Tho*_*que 12 .net c# vb.net clr events
我想知道这些EventInfo.GetRaiseMethod和EventInfo.GetOtherMethods方法.显然,CLR支持4种与事件相关的方法:添加,删除,提升和"其他".但是在C#中创建的事件只有添加和删除 ...我假设在VB中使用了raise,因为你必须RaiseEvent在声明自定义事件时指定一个方法,但显然情况并非如此:GetRaiseMethod始终返回null.
那么,有谁知道:
GetOtherMethods?他们应该做什么?据我所知,加注并没有太多使用,我几乎从未见过它.C++/CLI几乎是我所知道的唯一一种语言,可以很容易地声明一个raise方法.请参阅此代码示例:
using namespace System;
ref class Foo {
private:
Action ^bar;
public:
event Action ^Bar {
void add (Action ^action)
{
Console::WriteLine ("add");
bar += action;
}
void remove (Action ^action)
{
Console::WriteLine ("remove");
bar -= action;
}
void raise ()
{
Console::WriteLine ("raise");
if (!bar)
return;
Console::WriteLine ("raise for real");
bar->Invoke ();
}
};
};
void hello ()
{
Console::WriteLine ("hello");
}
void main ()
{
Foo ^foo = gcnew Foo ();
foo->Bar ();
foo->Bar += gcnew Action (&hello);
foo->Bar ();
}
Run Code Online (Sandbox Code Playgroud)
在运行时,自然输出:
C:\tmp>test
raise
add
raise
raise for real
hello
Run Code Online (Sandbox Code Playgroud)
要回答你的问题,没有操作码来调用事件,编译器只会调用raise方法:
IL_0020: ldloc.0
IL_0021: call instance void Foo::raise_Bar()
Run Code Online (Sandbox Code Playgroud)
就像它发出add_Bar调用一样.
由于C#允许您仅在声明成员事件的类型范围内调用事件,因此无法获得C#代码来调用该raise方法,这也是值得的.所以不,你不会在BCL中发现这样的方法.
至于.other那种方法,我从来没有看到任何附加到事件.我只看到它们曾经用过一次属性,而且"Inside IL汇编程序"和"CLI注释标准"这本书都没有提供有关它们的任何信息.但基本上,它们允许您将方法附加到属性或事件以在语义上绑定它们.它们既不是一种addon,也不是removeon一种raise方法,但如果语言需要表达,它们将成为事件的一部分.与此同时,发射一个的唯一方法是使用ilasm.