我一直在为我们公司遇到的一个复杂问题寻找解决方案。该公司是覆盖我国四个“区域”的 4 家公司联盟的一部分。 我们的分支机构用 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();
}
}
这样,在没有接口(interface)的情况下,每个分支都可以覆盖他们想要的任何方法,而不会影响其他分支。您只需将方法代码移动到 VStrategy 类并在您自己的区域类中覆盖它。
希望这对可能遇到这种情况的任何人有所帮助。
最佳答案
正如 Maurice Stam 所说,封装变化。乍一看,我会使用策略模式: http://www.oodesign.com/strategy-pattern.html
public interface IStrategy
{
ComplexReturnType MyMethod();
}
public class NationalDefaultStrategy : IStrategy
{
public ComplexReturnType MyMethod() { }
}
public class BostonStrategy: IStrategy
{
public ComplexReturnType MyMethod() { }
}
public class MyClass
{
private static IStrategy _strategy = new NationalDefaultStrategy();
public static ISTrategy Strategy { get {...}; set {...} }
public static ComplexReturnType MyMethod()
{
return _strategy.MyMethod();
}
}
这样,您可以轻松地更改运行时使用的策略
MyClass.Strategy = new BostonStrategy();
如果您将其设为实例方法而不是静态方法(我可能会这样做)并决定使用像 CaSTLe Windsor 这样的 IoC 容器,您甚至可以在配置文件中连接该策略。
编辑
从逻辑上讲,每个分支都有自己的配置文件。使用这种方法有两个优点:
- 所有分支将使用相同的代码库
- 您的代码将遵守开闭原则,即您的类应该对修改关闭,对扩展开放:http://en.wikipedia.org/wiki/Open/closed_principle .
关于c# - 我如何在部分类中使用 "override"方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18889247/