如何使用自定义对象的类型序列化列表列表? [英] How to serialize a list of lists with the type of custom object?

查看:28
本文介绍了如何使用自定义对象的类型序列化列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

    [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.

抱怨无法隐式投射等等,

Complains about not being able to implicitly cast it blah blah blah,

谁能知道这段代码有什么问题?

Anyone can tell what is wrong with this code?

推荐答案

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

Foo and FooContainer need to be public. Other than that it worked fine for me. Had to flesh out the code a bit, but his works ...

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; } }
}

这篇关于如何使用自定义对象的类型序列化列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆