【问题标题】:How to serialize a list of lists with the type of custom object?如何序列化具有自定义对象类型的列表列表?
【发布时间】:2009-07-26 00:58:15
【问题描述】:

代码如下:

    [XmlRoot("Foo")]
    class Foo
    {
        [XmlElement("name")]
        string name;
    }

    [XmlRoot("FooContainer")]
    class FooContainer
    {
        [XmlElement("container")]
        List<List<Foo>> lst { get; set; }
    }

    XmlSerializer s = new XmlSerializer(typeof(FooContainer)); -->Can't pass through this.

抱怨无法隐式投射它等等等等,

谁能说出这段代码有什么问题?

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

    Foo 和 FooContainer 需要公开。除此之外,它对我来说效果很好。 不得不稍微充实一下代码,但他的作品......

    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer s = new XmlSerializer(typeof(FooContainer));
    
            var str = new StringWriter();
            var fc  = new FooContainer();
    
            var lst = new List<Foo>() { new Foo(), new Foo(), new Foo() };
    
            fc.lst.Add( lst );
    
            s.Serialize(str, fc);
        }
    }
    
    [XmlRoot("Foo")]    
    public class Foo    {        
        [XmlElement("name")]        
        public string name = String.Empty;    }    
    
    [XmlRoot("FooContainer")]    
    public class FooContainer    {
    
        public List<List<Foo>> _lst = new List<List<Foo>>();
        public FooContainer()
        {
    
        }
    
        [XmlArrayItemAttribute()]
        public List<List<Foo>> lst { get { return _lst; } }
    }
    

    【讨论】:

    【解决方案2】:

    我知道有人会提到公开,所以我会跳到这里:

    是的,它们需要公开,但这不是唯一的问题。实际上运行序列化不起作用(得到描述的错误)

    它不喜欢列表

    [XmlRoot("Foo")]
    public class Foo
    {
        [XmlElement("name")]
        public string name;
    }
    
    [XmlRoot("FooContainer")]
    public class FooContainer
    {
        [XmlElement("container")]
        public List<SerializableList<Foo>> lst { get; set; }
    }
    
    [XmlRoot("list")]
    public class SerializableList<T>
    {
        [XmlElement("items")]
        public List<T> lst { get; set; }
    }
    

    【讨论】:

    猜你喜欢
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    相关资源
    最近更新 更多