2012-03-16 34 views
4

有誰知道在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的這些實現可以在一個完全不同的課,而不會訪問源。此外,如果有人隨後出現並更改了應該符合某個代表的方法簽名,則源代碼將會中斷,但它可能會在完全不同的模塊中靜默地中斷。

感謝您的任何幫助。

回答

4

C#不支持這一點。

但是,您可以通過簡單地把方法爲代表模擬它:

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

更改方法或委託簽名會導致編譯器錯誤一條線上面的方法。

(這樣做與實例方法需要一個構造函數調用)

爲了增加效率,你可以在未使用嵌套類和/或#if DEBUG做到這一點。

無論哪種方式,請務必留下解釋性評論。

4

委託具有返回類型和參數(類型和順序)組成的簽名 - 如果你有一個相匹配的簽名,它將匹配的委託方法。

你問的方法是static沒有區別。

還有就是要確保任何特定的方法,將符合委託簽名沒有直接的方法 - 你可以創建接口,符合簽名,並確保其使用和實現的方法。

0

如果不要求使用代表,您可以使用下面的模式。

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; 
} 
+1

AKA,Java的代表 – SLaks 2012-03-16 19:20:23

相關問題