有誰知道在C#中的一種方式來強制一個方法來「實現」一個委託?做一個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的這些實現可以在一個完全不同的課,而不會訪問源。此外,如果有人隨後出現並更改了應該符合某個代表的方法簽名,則源代碼將會中斷,但它可能會在完全不同的模塊中靜默地中斷。
感謝您的任何幫助。
AKA,Java的代表 – SLaks 2012-03-16 19:20:23