具有几乎相同的方法的C#扩展

问题描述:

对C#还有一点新鲜感,我有一个“实用程序”类,我想跨多个内部项目使用它。在一个项目中有一个巨大的(数百个属性,不是我在做的......)内部对象(SpecialObj)。其他项目无法访问此对象,并将它添加到它们是非启动器,所以基本方法不知道SpecialObj具有几乎相同的方法的C#扩展

所以,这里是rub:MyClass中的MyMethod(不需要这个特殊对象)和MyClassExtension(不需要特殊对象)具有几乎相同的代码,除了使用这个特殊对象的中间部分。

public class MyClass{ 
    public string MyMethod (string param1, Dictionary<string, string> param2){ 
     //some code in here part 1 
     //some code in here part 2 
    } 
} 

public class MyClassExtension : MyClass{ 
    public string MyMethod (string param1, Dictionary<string, string> param2, SpecialOjb param3) 
    { 
     //some code in here part 1 
     //something with param3, my special object 
     //some code in here part 2 
    } 
} 

在两种方法中保持90%相同的代码似乎......非常错误。这种情况是否有任何示例或标准?

+7

不能你'这里第1部分的一些代码'和'一些代码在这里第二部分'出两个其他方法? –

+0

MyClass :: MyMethod'可以调用MyClassExtension :: MyMethod吗? – Igor

+0

@DanDumitru这真的是一个非常好的想法......也许,我会尝试。 –

您可以将代码分成保护的部分,并呼吁他们

public class MyClass 
{ 
    public string MyMethod (string param1, Dictionary<string, string> param2) 
    { 
     ProtectedMyMethodPart1(...); 
     ProtectedMyMethodPart2(...); 
    } 

    protected void ProtectedMyMethodPart1(...) 
    { 
    } 

    protected void ProtectedMyMethodPart2(...) 
    { 
    } 
} 

和重用他们在继承类

public class MyClassExtension : MyClass 
{ 
    public string MyMethod (string param1, Dictionary<string, string> param2, SpecialOjb param3) 
    { 
     ProtectedMyMethodPart1(...); 
     // Do something with param3 
     ProtectedMyMethodPart2(...); 
    } 
} 

也许我会做这样的事情。

public class MyClass{ 
    public virtual string MyMethod (string param1, Dictionary<string, string> param2){ 
     int i= MyCommonCode.MyCommonMethod(); 
     //I do whatever I like with i here 
    } 
} 

public class MyClassExtension : MyClass{ 
    public string MyMethod (string param1, Dictionary<string, string> param2, SpecialOjb param3) 
    { 
     int i= MyCommonCode.MyCommonMethod(); 
     //I do whatever I like with i here 
    } 
} 

public class MyCommonCode 
{ 
    public static int MyCommonMethod() 
    { 
    return 1; 
    } 
}