使 C# 方法“实现”委托

MgS*_*Sam 4 .net c# methods delegates interface

有谁知道 C# 中强制方法“实现”委托的方法?

考虑这个大大简化的例子:(大致基于我遇到的真实世界场景)

    private delegate int ComputationMethod(int termA, int termB, int termC, int termD);

    private int computationHelper(int termA, int termB, int termC, int termD, ComputationMethod computationMethod)
    {
        //Some common logic^
        int answer = computationMethod(termA, termB, termC, termD);
        //Some more common logic^
        return answer;
    }

    public int ComputeAverage(int termA, int termB, int termC, int termD)
    {
        //^^
        return computationHelper(termA, termB, termC, termD, computeAverage);
    }

    public int ComputeStandardDeviation(int termA, int termB, int termC, int termD)
    {
        //^^
        return computationHelper(termA, termB, termC, termD, computeStandardDeviation);
    }        

    //Is there some way to force this method's signature to match ComputationMethod?
    private static int computeAverage(int termA, int termB, int termC, int termD) 
    {
        //Implementation omitted
    }

    //Is there some way to force this method's signature to match ComputationMethod?
    private static int computeStandardDeviation(int termA, int termB, int termC, int termD)
    {
        //Implementation omitted
    }
Run Code Online (Sandbox Code Playgroud)

^ - 假设无法从 ^^ 调用此逻辑。

在这个例子中,我基本上想“强制”方法符合 ComputationMethod 签名,就像接口强制一个类实现某些方法一样。相当于:

private static int computeAverage(int termA, int termB, int termC, int termD) : ComputationMethod
    {
        //Implementation omitted
    }
Run Code Online (Sandbox Code Playgroud)

是的,显然我可以只复制和粘贴方法签名,但从概念上讲,这些 ComputationMethod 的实现可以在一个完全不同的类中,而无需访问源代码。此外,如果有人随后更改了应该符合某个委托的方法签名,则源代码将中断,但它可能会在完全不同的模块中静默中断。

谢谢你的帮助。

SLa*_*aks 5

C# 不支持这个。

但是,您可以通过简单地将方法放入委托来模拟它:

static readonly ComputationMethod _ForceCompliance = ComputeAverage;
private static int ComputeAverage(int termA, int termB, int termC, int termD) { ... }
Run Code Online (Sandbox Code Playgroud)

更改方法或委托签名会导致在方法上方一行出现编译器错误。

(使用实例方法执行此操作需要构造函数调用)

为了提高效率,您可以在未使用的嵌套类和/或#if DEBUG.

无论哪种方式,请务必留下解释性评论。