开发者

XML Serialization of an Interface

开发者 https://www.devze.com 2023-01-20 19:52 出处:网络
I have a problem that I\'m working in nHibernate projec开发者_如何学JAVAt that have the following object:

I have a problem that I'm working in nHibernate projec开发者_如何学JAVAt that have the following object:

[Serializable]
public class Prototype
{
    public virtual long Id { get; private set; }
    public virtual string Name { get; set; }   
    public virtual IList<AttributeGroup> AttributeGroups { get; private set; }
}

I have created a method to deserialize an XML file and put it into object of type Prototype as following :

public static T Deserialize(string fileName)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    XmlTextReader xmlTextReader = new XmlTextReader(fileName);
    Object c = xmlSerializer.Deserialize(xmlTextReader);
    return (T)c;
}

The problem now is that I have the following exception:

Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag`1[BCatalog.Entities.AttributeGroup]' to type 'System.Collections.Generic.List`1[BCatalog.Entities.AttributeGroup]'.

I can't change the type of the IList because of the nHibernate and I want to deserialize the object.

What should I do to solve this problem ?


Interfaces seems to be cumbersome for serialization/deserialization processes. You might need to add another public member to the class that uses a concrete type and mark the interface property as xml ignore. This way you can deserialize the object without loosing your contract base.

Something like the following:

[Serializable]
public class Prototype
{
    public virtual long Id { get; private set; }
    public virtual string Name { get; set; }   
    [XMLIgnore]
    public virtual IList<AttributeGroup> AttributeGroups { 
        get { return this.AttributeGroupsList; } 
    }
    public virtual List<AttributeGroup> AttributeGroupsList { get; private set;}
}

For more information about deserialization attributes please check XmlAttributes Properties.

Regards,

0

精彩评论

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