【发布时间】:2013-09-24 05:12:48
【问题描述】:
我一直在寻找解决我们公司遇到的复杂问题的方法。该公司是覆盖我国四个“地区”的四家公司联盟的一部分。 我们的分支用 C# 开发了一个 WebService,我们将这个项目分发给其他分支的开发人员。每个人都在自己的服务器中托管 WebService。
现在,当公司相处不融洽时,我一直在为一些你可以期待的事情苦苦挣扎。我必须调整现有方法以适应我们的“区域需求”。
所以我有这门课:
public partial class MyClass{
public static ComplexReturnType MyMethod(){
// National code. Everyone uses this block of code.
}
}
我创建了一个区域文件夹,在将 DLL 分发到其他分支时,我将从编译中排除该文件夹。在这个文件夹中,我创建了文件 MyClass.cs 并继续:
public partial class MyClass{
public static ComplexReturnType MyMethod(){
// Regional code. Only my commpany will use this.
}
}
方法MyMethod在其他文件中被调用。我了解partial 的工作原理,但如果不创建子类并重写其他文件中已经存在的每个调用,我就找不到适合我需求的解决方案。
有人知道如何处理这个问题吗?
回答后编辑
我决定采用策略设计模式,完成后我想“如果一个分支决定覆盖任何方法,所有其他分支都必须使用其区域策略类中的国家代码覆盖相同的方法” .
所以这不是很好。相反,我这样做了:
public class VStrategy
{
public virtual ComplexReturnType MyMethod(){
// National code. Method moved from MyClass
}
public virtual AnotherReturnType MySecondMethod(){
// National code. Method moved from MyClass
}
}
public class SomeBranchStrategy: VStrategy
{
public override ComplexReturnType MyMethod() {
// Regional code for overriding a method
}
}
public class AnotherBranchStrategy: VStrategy
{
public override AnotherReturnType MySecondMethod(){ {
// Regional code for overriding a method
}
}
public class MyClass
{
private static VStrategy _strategy = new VStrategy();
public static VSTrategy Strategy { get {...}; set {...} }
public static ComplexReturnType MyMethod()
{
return Strategy.MyMethod();
}
public static ComplexReturnType MySecondMethod()
{
return Strategy.MySecondMethod();
}
}
这样,在没有接口的情况下,每个分支都可以覆盖他们想要的任何方法,而不会影响其他分支。您只需将方法代码移至 VStrategy 类并在您自己的区域类中覆盖它。
希望这可以帮助任何可能处于这种情况的人。
【问题讨论】:
-
结果应该选择哪种方法?
-
if(myCompany){MyCompanyMethod();} else {OtherMethod();} -
看起来你正在通过使用部分类使问题变得更复杂。恕我直言,使用良好的“对象组合/继承”将是可行的方法。
-
@Extra:现在您已经亲身体验了为什么
static容易导致开发死胡同。如果该方法是virtual(和/或接口的一部分),那么用更专业的类的实例替换调用它的实例将是一个“简单”的事情(您不需要重写每个称呼)。把课带回家。
标签: c#