Mar*_*rco 5 c# oop reflection overriding design-patterns
情况:
Assembly 1
________________________ ________________________
| Class A | | Class B |
|-----------------------| |-----------------------|
| Method someMethod |---------->| Method otherMethod |
| | | |
|_______________________| |_______________________|
Run Code Online (Sandbox Code Playgroud)
程序集1是其他开发人员可以使用的应用程序.我们只给他们.dll所以如果我们不改变api,我们可以从应用程序发布更新.开发人员无法更改程序集1中的框架
方法是虚拟的,因此开发人员可以覆盖方法以在需要时实现自己的逻辑.
问题是开发人员不能覆盖B类中的otherMethod,他可以覆盖它,但A类总是从B类调用方法而不是覆盖方法.
Assembly 1
________________________ ________________________
| Class A | | Class B |
|-----------------------| |-----------------------|
| Method someMethod |----XX---->| Method otherMethod |
| | | |
|_______________________| |_______________________|
\ |
\ |
\ |
Assembly 2 \ |
\ ________________|_______
\ | Class ExtendedB |
\ |-----------------------|
\____________>| Method otherMethod |
| |
|_______________________|
Run Code Online (Sandbox Code Playgroud)
组件2具有组件1的参考
部分类不起作用,因为它必须是相同的程序集,并且不能超过2
这个问题有设计模式吗?或者是否有其他解决方案或反射?
编辑添加了一个代码示例:
/* ASSEMBLY 1 */
namespace Assembly1
{
public interface IAService
{
void TestMethod3();
void TestMethod4();
}
public interface IBService
{
void TestMethod1();
void TestMethod2();
}
public class AService : IAService
{
// Base implementation of AService
public virtual void TestMethod3()
{
//do something
}
public virtual void TestMethod4()
{
//do something
}
}
public class BService : IBService
{
// Base implementation of BService
public virtual void TestMethod1()
{
//do something
}
public virtual void TestMethod2()
{
//need to call AService implementation from assembly 2
}
}
}
/* ASSEMBLY 2 */
namespace Assembly2
{
public class NewAService : AService
{
public override void TestMethod3()
{
//default implementation which could be overridden
base.TestMethod3();
}
public override void TestMethod4()
{
//default implementation which could be overridden
//An implementation of IBService Should be called
base.TestMethod4();
}
}
}
Run Code Online (Sandbox Code Playgroud)
你应该重构
public interface IClassB
{
void SomeMethod();
}
public Class A
{
private IClassB myInstanceB = new ClassB();
public ClassA(){}
public ClassA(IClass B)
{
myInstanceB = B;
}
public void SomeMethod()
{
myInstanceB.SomeMethod();
}
}
public ClassB : IClassB
{
public void SomeMethod()
{
// some wicked code here...
}
}
Run Code Online (Sandbox Code Playgroud)
完成此重构后,开发人员可以通过使用空构造函数来使用默认实现。如果他们需要一些其他逻辑,那么他们只需实现接口 IClassB 并将其传递到其他构造函数中即可。
程序集 2 中的用法是这样的
public class NewFunctionalityClass : IClassB
{
public void SomeMethod()
{
//something else
}
}
public TestClass()
{
public void ShowMethod()
{
var defaultObject = new ClassA();
defaultObject.SomeMethod(); // default implementation
var otherObject = new ClassA(new NewFunctionalityClass());
otherObject.SomeMethod(); // here the new implementation will run
}
}
Run Code Online (Sandbox Code Playgroud)