A member function should change the instance of the calling object. But my recent attempts didn't change the instance.
I want to provide a base class, which implements a function to deserialize a string (or file) to an object of the child class.
Is it even possible to do such thing?
EDIT: Ok lets forget the extension method. Another attempt was:
class ChildClass : BaseClass
{
[XmlAttribute(AttributeName = "atribute")]
public string Atribute { set; get; }
}
class BaseClass
{
public void Deserialize(string filePath)
{
using (StreamReader reader = new StreamReader(filePath))
{
XmlSerializer serializer = new XmlSerializer(this.GetType());
return (BaseClass)serializer.Deserialize(reader);
}
}
}
class Program
{
public void Main()
{
ChildClass foo = new ChildClass();
// looks pretty bad and seems quite inconvenient to me
foo = (ChildClass)foo.Deserialize("file.xml")
}
}
What I "need" is something like:
class BaseClass
{
public void Deserialize(string filePath)
{
using (StreamReader reader = new StreamReader(filePath))
{
XmlSerializer serializer = new XmlSerializer(this.GetType());
this = (BaseClass)serializer.Deserialize(reader);
}
}
}
Or can I use the constructor?
Best regards, Martin
BaseClass
, it shouldn't use the parameter passed in. – DavidGDeserialize
is NOT a member function. It's an extension method doesn't that return the object it deserializes. It usesbar
as if it were a temporary variable – Panagiotis Kanavos