从 C# 中的泛型引用调用派生类重写方法
我正在构建一个游戏,并且有基本的继承层次结构:
GameObject
是一个基类,有一个名为 Clone
的虚拟方法
PlatformObject
派生自GameObject
,重写 Clone
方法
我有一个针对任何 GameObject
的序列化器/反序列化器泛型类或定义如下的派生类:
public 类XmlContentReaderBase
我的 XML Reader 类不知道我的派生类型。我对这一行有一个问题:
T obj = serializer.Deserialize(input) as T;
return obj.Clone() as T;
第一行运行良好,并返回一个正确的 PlatformObject
。但第二行调用了基类GameObject
的Clone
方法,这不是我想要的。我需要调用 PlatformObject.Clone
方法,如何完成此操作?
谢谢, 能。
I'm building a game and there is basic inheritance hiearchy:
GameObject
is a base class, has a virtual method called Clone
PlatformObject
is derived from GameObject
, overriding the Clone
method
I have a serializer/deserializer generic class for any GameObject
or derivations defined as below:
public class XmlContentReaderBase<T> where T : GameObject
My XML Reader class is unaware of my derived type. I've got a problem with this line:
T obj = serializer.Deserialize(input) as T;
return obj.Clone() as T;
The first line runs fine, and returns a PlatformObject
which is correct. But the second line calls the Clone
method of the base class, GameObject
, which is not what I want. I need to call PlatformObject.Clone
method, how can I get this done?
Thanks,
Can.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我编写了一个与此非常接近的实现,并看到 Clone 引用派生对象的 Clone 方法(通过创建一个新对象而不是反序列化对象有点作弊)。
发布更多代码?
输出:
I wrote an implementation very close to this and see Clone referencing the derived object's Clone method (cheated a bit by creating a new object rather than deserializing one).
Post more code?
Output: