![](/img/trans.png)
[英]How to call generic method of derived class from base class reference in C#
[英]Calling derived class override method from generic reference in C#
我正在构建游戏,并且有基本的继承层次:
GameObject
是一个基类,具有一个称为Clone
的虚拟方法
PlatformObject
是从GameObject
派生GameObject
,它重写Clone
方法
对于任何定义如下的GameObject
或派生类,我都有一个序列化器/反序列化器通用类:
public class XmlContentReaderBase<T> where T : GameObject
我的XML Reader类不知道我的派生类型。 我对这条线有疑问:
T obj = serializer.Deserialize(input) as T;
return obj.Clone() as T;
第一行运行正常,并返回正确的PlatformObject
。 但是第二行调用基类GameObject
的Clone
方法,这不是我想要的。 我需要调用PlatformObject.Clone
方法,如何做到这一点?
谢谢,可以。
我写了一个非常接近此实现的实现,看到Clone引用了派生对象的Clone方法(通过创建一个新对象而不是反序列化一个对象而有点作弊)。
发布更多代码?
using System.Text;
namespace GenericExperiment
{
class Program
{
static void Main(string[] args)
{
XmlContentReaderBase<PlatformObject>.Deserialize();
Console.ReadKey();
}
}
class GameObject : ICloneable
{
object ICloneable.Clone()
{
Console.WriteLine("I am the base class");
return null;
}
}
class PlatformObject: GameObject, ICloneable
{
object ICloneable.Clone()
{
Console.WriteLine("I am the derived class");
return null;
}
}
class XmlContentReaderBase<T> where T : GameObject, new()
{
static public object Deserialize()
{
T obj = new T();
((ICloneable)obj).Clone();
return obj;
}
}
}
输出:
我是派生类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.