开发者

Why can't we serialize a concrete class which derives from an interface?

I don't understand why we can't serialize a concrete class that derives from an interface. The properties of the concrete class are still known!

public interface IThing
{
    string Name { get; }
}

[XmlRoot]
public class RealThing : IThing
{
    [XmlAttribute]
    public string Name { get { return "Real Thing"; } set{ /* Do something. */ } }
}

I've told the XmlSerializer what to do with the implemented property, why would this not work? Why would the XmlSerializer even look at the interface?

I've made a ton of serializable classes and am just running into this now. Is it possible that none of the hundreds of serializable classes I've made开发者_如何学Python in the past implemented an interface?


You certainly can serialize a class that inherits an interface. But you cannot tell the serializer to serialize the interface, because it wouldn't know which concrete class to instantiate on deserialization.

In other words serialization will work, if you instantiate your serializer like this:

XmlSerializer ser = new XmlSerializer(typeof(RealThing));
ser.Serialize(new MemoryStream(), new RealThing());

Also, you will need to make RealThing a public class, since that is required by Xmlserializer.


Your property needs a setter. The XML Serializer only serializes public, read/write properties.


I've just serialized RealThing ok with XmlSerializer.

Whatever your problem is, I don't think it's because RealThing implements an interface...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜