我们经常在C#中使用事件处理器,如下所示:
some_event+=some_event_handler;
这发生在编译时还是运行时?如果 some_event 是静态成员怎么办? AFAIK,some_event 只包含 some_event_handler 的入口地址,而 some_event_handler 的方法地址可以在编译时确定。如果 some_event 是静态成员,那么 some_event 的值是否可以在编译时确定?我知道如果 some_event 是一个实例成员,它的值将在对象实例的创建时设置。如果我错了,请纠正我。
非常感谢,伙计们~:)
最佳答案
我们可以说它涉及委托(delegate)
。 delegate
变量被动态分配了一个方法。这使我们能够编写插件方法。
Concerning instance and static method targets just a note from C# in Nutshell
When a delegate object is assigned to an instance method, the delegate object must maintain a reference not only to the method, but also to the instance to which the method belongs. The System.Delegate class’s Target property represents this instance (and will be null for a delegate referencing a static method).
关于c# - 事件处理程序注册何时发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3147316/