簡體   English   中英

為什么分配實例方法的委托存儲實例對象?

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

method已經是開始執行的位置的地址(它是一個int )。 大概這個地址與它所涉及的對象實例相關聯,那么為什么委托需要對象( Target )?

假設沒有存儲目標。 什么應該調用實例方法的委托呢? 如果沒有作為當前實例的對象引用(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM