【发布时间】:2019-03-02 23:33:36
【问题描述】:
这是我的问题: 我有一个在 B 类中多次使用(实例化)的 A 类。
我需要改变A类的行为,主要是构造函数,然后我用C类派生它。 C类:A类
我希望 B 类在其方法中使用 C 类而不是 A 类,避免覆盖所有使用它的方法。 这可能吗?
非常感谢
我不清楚,所以让我尝试用代码更好地解释。
Public Class A
{
`// Simple constructor
public A(params[])
{
// things here
}
}
Public Class C : A
{
// Constructor doing different thing then base
public C(params[]): base(params[])
{
// do different things here
}
}
Public class B
{
public B(params[])
{ }
public method_A(params[])
{
A _temp = new A(params[]);
// do things here with A
}
}
我在我的程序中使用 B,但我希望 B 的一个实例使用 A,而 B 的另一个实例使用 C 而不是 A。
类似:
Main()
{
B _instance1 = new B();
B _instance2 = new B();
// use instance 1
_instance1.method_A(...);
// use instance 2
_instance2.method_A(...); // do something here for using C instead of A in the method
}
【问题讨论】:
-
提供示例代码。
-
您能详细说明一下吗?也许一个简短的例子会有所帮助
-
将
B类中的new A()替换为new C()(当我正确理解您的问题时,应该进行此更改)。 -
听起来你想研究一下工厂模式。可能“只是”一个简单的工厂方法就足够了。因此,与其到处调用
new A(),不如使用一个 方法,如public A CreateA() { return new A(); },并在需要A的新实例时调用that。如果你这样做了,那么现在更改它会很容易:public A CreateA() { return new C(); }(因为C : A应该没有问题;除了命名可能)。你现在可能不得不硬着头皮重构这个,这样下次你需要D : A时会更容易。 -
感谢您的回答。我添加了一些注释和代码,这可能会有所帮助。这件事与我最初的糟糕问题有点不同。
标签: c# class overriding derived-class