使C#方法“实现”委托

时间:2012-03-16 16:59:42

标签: c# .net interface methods delegates

有没有人知道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
    }

^ - 假设这个逻辑不能从^^中调用

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

的东西
private static int computeAverage(int termA, int termB, int termC, int termD) : ComputationMethod
    {
        //Implementation omitted
    }

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

感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

委托具有由返回类型和参数(类型和顺序)组成的签名 - 如果您有一个与该签名匹配的方法,它将匹配该委托。

你问的方法是static没有区别。

没有直接的方法可以确保任何特定方法符合委托签名 - 您可以使用符合签名的方法创建接口,并确保使用和实现它。

答案 1 :(得分:4)

C#不支持此功能。

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

static readonly ComputationMethod _ForceCompliance = ComputeAverage;
private static int ComputeAverage(int termA, int termB, int termC, int termD) { ... }

更改方法或委托签名将导致编译器错误超出方法一行。

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

为了提高效率,您可以在未使用的嵌套类和/或#if DEBUG中执行此操作。

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

答案 2 :(得分:-1)

如果您不需要使用委托,则可以使用以下模式。

public interface IComputationMethod
{
    int ComputationMethod(int termA, int termB, int termC, int termD);
}

public class AverageComputer : IComputationMethod
{
    public override int ComputationMethod(int termA, int termB, int termC, int termD)
    {
    // omitted.
    }
}

public class StDevComputer : IComputationMethod
{
    public override int ComputationMethod(int termA, int termB, int termC, int termD)
    {
    // omitted.
    }
}

将计算助手的签名更改为:

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