簡體   English   中英

靜態委托數組中的實例方法

[英]Instance methods in static delegate array

我有一個很大的靜態的委托數組,對於該類的所有實例都是相同的。 我想在數組中放置對實例方法的引用,即打開實例委托 編譯器給我一個錯誤。 我怎么做?


示例代碼:

public class Interpreter
{
    // >7 instance fields that almost all methods need.

    private static readonly Handler[] Handlers = new Handler[]
    {
        HandleNop,          // Error: No overload for `HandleNop` matches delegate 'Handler'
        HandleBreak,
        HandleLdArg0,
        // ... 252 more
    };

    private delegate void Handler(Interpreter @this, object instruction);

    protected virtual void HandleNop(object instruction)
    {
        // Handle the instruction and produce a result.
        // Uses the 7 instance fields.
    }

    protected virtual void HandleBreak(object instruction) {}
    protected virtual void HandleLdArg0(object instruction) {}
    // ... 252 more
}

我考慮過一些想法:將所有實例字段作為參數提供,但這很快就變得很笨拙。 初始化每個實例的處理程序列表,但這會嚴重影響性能(我需要該類的許多實例)。

根據喬恩·斯凱特(Jon Skeet)對另一個問題的回答 ,以下將起作用:

public class Interpreter
{
    private static readonly Handler[] Handlers = new Handler[]
    {
        (@this, i) => @this.HandleNop(i),
        (@this, i) => @this.HandleBreak(i),
        (@this, i) => @this.HandleLdArg0(i),
        // ... 252 more
    };

    private delegate void Handler(Interpreter @this, object instruction);

    protected virtual void HandleNop(object instruction) {}
    protected virtual void HandleBreak(object instruction) {}
    protected virtual void HandleLdArg0(object instruction) {}
}

C#的直接支持會更好。 也許還有另一種不涉及間接和額外輸入的方法嗎?

暫無
暫無

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

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