Why does a delegate assigned an instance method store the instance object?

StackOverflow https://stackoverflow.com/questions/19196009

  •  30-06-2022
  •  | 
  •  

Вопрос

The method is already the address (it's an int) of the location to begin execution. Presumably this address is associated with the object instance it relates to, so why does the delegate need the object (Target)?

Это было полезно?

Решение

Assume that the target was not stored. What should invoking a delegate to an instance method do? An instance method cannot run without an object reference that is the current instance (the this reference in C#). It is not possible to define a sensible behavior for this case.

An instance method can access instance fields. Without the this reference these fields would be inaccessible.

If you do not want to store the target, wrap the instance method in a static function:

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top