2009-12-11 109 views
1

從某種程度上來說,這更像是一個思考練習,而不是一個真正的問題,因爲我沒有足夠的CustomFS類受到僅使用複製粘貼的困擾。但我想知道是否有更好的方法。「heritance」覆蓋函數

假設我有幾類CustomFSCustomFS2,等等,所有這些都來自FSFS2等FS/FS2 /等繼承。全部從FSG繼承,它具有功能GetStuff。假設我沒有修改FS和FSG的能力,我如何在只有一個CustomFS類的FS/FS2許多中重寫某個特定函數,並且不用FS構造CustomFS併爲所有FS的方法添加包裝函數customFS。

當前的戰略:複製/粘貼:

class CustomFS : FS 
{ 
    protected override int GetStuff(int x) 
    { 
     int retval = base.GetStuff(x); 
     return retval + 1; 
    } 
} 

class CustomFS2 : FS2 
{ 
    protected override int GetStuff(int x) 
    { 
     int retval = base.GetStuff(x); 
     return retval + 1; 
    } 
} 
+0

注意:重載函數並不足夠複雜以至於無法添加額外的間接層。 – Brian 2009-12-12 12:52:04

回答

1

你不能,除非通過代理的方式或者通過Reflection.Emit的發射自己的派生類。但是,如果您需要在每個類上執行更復雜的功能,則可能需要創建一個輔助方法(可能是通用的和靜態的),它可以完成實際的工作。

1

如果我正確理解你的問題,這似乎是一個不錯的選擇的戰略設計模式:http://www.dofactory.com/patterns/patternstrategy.aspx

這可能纔有意義,如果你的重載函數比幾行更爲複雜。但是,基本上,你可以有一個類StuffGetter將有自己的方法GetStuff

public class StuffGetter 
{ 
    public int GetStuff(int rawStuff) 
    { 
     return rawStuff + 1 // presumably, the real example is more complicated than this 
    } 
} 

然後,你會做這樣的事情:

class CustomFS : FS 
{ 
    private StuffGetter _stuffGetter { get; set; } 

    public CustomFS(StuffGetter stuffGetter) 
    { 
     _stuffGetter = stuffGetter; 
    } 

    protected override int GetStuff(int x) 
    { 
     int retval = base.GetStuff(x); 
     return _stuffGetter.GetStuff(retval); 
    } 
} 

class CustomFS2 : FS2 
{ 
    private StuffGetter _stuffGetter { get; set; } 

    public CustomFS2(StuffGetter stuffGetter) 
    { 
     _stuffGetter = stuffGetter; 
    } 

    protected override int GetStuff(int x) 
    { 
     int retval = base.GetStuff(x); 
     return _stuffGetter.GetStuff(retval); 
    } 
} 

基本上,你在StuffGetter實例傳遞給任何類需要您的自定義GetStuff實施。作爲替代,你可以讓StuffGetter成爲一個靜態類(這會讓你免於需要傳入一個實例),但這不太靈活。例如,如果您想根據實際情況需要兩種不同的實現,則可以僅傳入(並存儲)包含所需實現的實例。

0
class CustomFS : FS 
{ 
    protected override int GetStuff(int x) 
    { 
     return CustomHelper.GetStuff(base.GetStuff(x)); 
    } 
} 

class CustomFS2 : FS2 
{ 
    protected override int GetStuff(int x) 
    { 
     return CustomHelper.GetStuff(base.GetStuff(x)); 
    } 
} 

static class CustomHelper 
{ 
    static int GetStuff(int x) 
    { 
     return x + 1; 
    } 
}