[英]C# change type of child class in parent(abstract) class
码:
abstract class Parent{
void changeChild(){
}
}
class Child1: Parent{
}
class Child2: Parent{
}
//-----
Parent parent = new Child1(); //instantiated as Child1
parent.changeChild(); //change type of this class to Child2
因此父级应该是Child2类的实例。
我知道Child1可以不同于Child2(更多/更少的字段,方法),但是我只想在此对象上调用构造函数,这是不允许的。
简单
parent = new Child2();
可以完成,但是有大约10个子类(正在增长),我想将其移到父类中
在C#中这有可能吗?
谢谢
您不能更改现有对象的类型,但是可以创建一个新对象并将其返回。
例:
abstract class Parent{
Parent ChangeChild<T>() where T : Parent {
if (typeof(T) == typeof(Child1)) {
return new Child1(this);
if (typeof(T) == typeof(Child2)) {
return new Child2(this);
} else {
throw new NotImplementedException("Unhandled type");
}
}
}
class Child1: Parent{
public Child1() {} // create
public Child1(Parent source) {} // convert
}
class Child2: Parent{
public Child2() {} // create
public Child2(Parent source) {} // convert
}
Parent parent = new Child1();
parent = parent.ChangeChild<Child2>();
好吧,如果您只想自动调用ctor,应该足以使某些东西变形,例如
class Child1: Child2{
}
class Child2: Parent{
}
所以,你必须Child2
构造函数时,将调用Child1
构造。 但是就您而言,这是完全不同的体系结构设计。
如果不是您要的东西,请澄清一下。
Automapper可能是您最好的选择。
T changeChild<T>() : Parent{
// change the type here.
}
这样的事情行吗?
abstract class Parent {
private Parent Proxy;
public void ChangeChild<T>() where T : Parent, new() {
Proxy = new T();
}
}
您必须使用Proxy
对象来调用成员和属性。
你不能这样做。 也许您可以将Parent
创建为包装器类
class Parent
{
Parent _child;
public Parent(Parent child)
{
_child = child;
}
public void ChangeChild(Parent child)
{
_child = child;
}
public string AProperty {
get { return _child.AProperty; }
set { _child.AProperty = value; }
}
public int AMethod(int x)
{
return _child.AMethod(x);
}
}
接着
Parent parent = new Parent(new Child1());
parent.AProperty = "hello";
int y = parent.AMethod(55);
parent.ChangeChild(new Child2());
注意:在良好的OO设计中,父母不应该了解有关特定孩子的知识。 这样可以确保您以后可以创建新的子代(例如Child3
)而不必更改Parent
。
但是,如果这不是您的问题,并且您希望父项自动关心更改子项,则使用以下方法更改或重载构造函数:
public Parent()
{
_child = new Child1();
}
并更改或重载ChangeChild
public void ChangeChild()
{
if (_child is Child1) {
_child = new Child2();
} else {
_child = new Child1();
}
}
如果需要在运行时更改某些对象的类型,则继承不是这种情况。 您应该在这里使用合成。 尝试类似策略 (如果Parent
类代表某种行为)的方法。
public class Foo
{
// provide default value (or inject it via ctor)
private Parent _parent = new Child1();
public void ChangeChild(Parent parent){
_parent = parent;
}
public void Bar()
{
_parent.DoSomething();
}
}
public abstract class Parent
{
public abstract void DoSomething();
}
public class Child1: Parent
{
public override void DoSomething() { ... }
}
public class Child2: Parent
{
public override void DoSomething() { ... }
}
现在,您可以在运行时更改依赖项的类型:
Foo foo = new Foo(new Child1());
foo.Bar(); // child1 implementation used
foo.ChangeChild(new Child2());
foo.Bar(); // child2 implementation used
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.