c# - 事件处理程序注册何时发生?

标签 c# .net

我们经常在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/

相关文章:

c# - AutoMapper 模拟 UnitOfWork 失败

C# 有 foreach oneliner 可用吗?

c# - 为什么相同的异常有不同的错误代码?

c# - SelectList 没有选择正确的值

c# - 无法使用 Selenium Webdriver 打开 chrome 浏览器。管理员禁止加载解压的扩展

c# - 在 OnResultExecuting 中更改 filterContext.Result

c# - 在 null IEnumerables 上为 Count() 返回零

c# - 移动列表中的元素

c# - LINQ:使用 AND 序列构建动态过滤器

c# - 以编程方式触发 ListView.SelectedIndexChanged 事件?