有没有办法在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的实现可能完全在没有源代码访问权限的另一个类中。此外,如果有人更改了应符合某个委托的方法签名,源代码将会出错,但它可能会在完全不同的模块中默默地出错。
感谢您的任何帮助。