2009-12-11 187 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; 
    } 
}