using namespace System; ref strUCt A { static int Square(int i) { return i * i; } }; ref struct B { int Cube(int i) { return i * i * i; } }; /*1*/ delegate int Del(int value);
int main() { /*2*/ Del^ d = gcnew Del(&A::Square); /*3*/ Console::WriteLine("d(10) result = {0}", d(10)); /*4*/ B^ b = gcnew B; /*5*/ d = gcnew Del(b, &B::Cube); /*6*/ Console::WriteLine("d(10) result = {0}", d(10)); } 静态函数A::Square与实例函数B::Cube对Del来说,都具有相同的参数类型及返回类型,因此它们能被包装进同类型的代理中。注重,即使两个函数均为public,当考虑它们与Del的兼容性时,它们的可访问性也是不相关的,这样的函数也能被定义在相同或不同的类中,主要由程序员来选择。
Client A received message Message 2 Client A received message Message 3 Client B received message Message 3 Client A received message Message 4 Client B received message Message 4 Client C received message Message 4 Client B received message Message 5 Client C received message Message 5 Client C received message Message 6 尽管3个对象均为同一类型,但这并不是必须的,只要定义的函数可与NewMsgEventHandler兼容,就能使用任意的类型。