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.
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?
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;
}
}
}
Output:
I am the derived class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.