为什么分配实例方法的委托存储实例对象?

时间:2013-10-05 09:11:26

标签: c# delegates il

method已经是要开始执行的位置的地址(它是int)。大概这个地址与它所涉及的对象实例相关联,那么为什么委托需要对象(Target)?

1 个答案:

答案 0 :(得分:3)

假设未存储目标。什么应该调用实例方法的委托呢?如果没有作为当前实例的对象引用(C#中的this引用),则实例方法无法运行。对于这种情况,不可能定义合理的行为。

实例方法可以访问实例字段。如果没有this引用,这些字段将无法访问。

如果您不想存储目标,请将实例方法包装在静态函数中:

MyCustomClass obj = new MyCustomClass();
Action withTarget = obj.SomeMethod; //stores target

static void MyCustomInvoker(MyCustomClass obj) {
 obj.SomeMethod();
}

Action<MyCustomClass> noTarget = MyCustomInvoker; //does not store any target