如何与QUOT;克隆QUOT;对象成子类对象? [英] How to "clone" an object into a subclass object?

查看:167
本文介绍了如何与QUOT;克隆QUOT;对象成子类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 A 和类 B 继承类 A 并与一些更多的领域进行了扩展。

I have a class A and a class B that inherits class A and extends it with some more fields.

具有物 A型 A ,如何创建类型的对象 b b 包含该对象中所有数据 A 载?

Having an object a of type A, how can I create an object b of type B that contains all data that object a contained?

我曾尝试 a.MemberwiseClone(),但只给了我另一种类型的 A 对象。我不能投 A B 自继承关系只允许相反的演员。

I have tried a.MemberwiseClone() but that only gives me another type A object. And I cannot cast A into B since the inheritance relationship only allows the opposite cast.

什么是做到这一点的正确方法?

What is the right way to do this?

推荐答案

有自动做这个没有办法内置的语言...

There is no means of doing this automatically built into the language...

一种选择是添加一个构造函数,b类,需要一个A类作为参数。

One option is to add a constructor to class B that takes a class A as an argument.

然后,你可以这样做:

B newB = new B(myA);



构造可以复制整个需要的相关数据,在这种情况下。

The constructor can just copy the relevant data across as needed, in that case.

这篇关于如何与QUOT;克隆QUOT;对象成子类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆