在 C# 中序列化嵌套类? [英] Serialize Nested Classes in c#?

查看:70
本文介绍了在 C# 中序列化嵌套类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是序列化嵌套类.我的代码第一:

What I'm trying to do is serialize Nested classes. My code first:

[Serializable]
public class SampleClass
{
    [Serializable]
    public class Person
    {
        [XmlElement("Name")]
        public string Name { get; set; }
        [XmlElement("Age")]
        public ushort Age { get; set; }
    }
    [Serializable]
    public class Adress 
    {
        [XmlElement("Street")]
        public string Street { get; set; }
        [XmlElement("House number")]
        public int Number { get; set; }
    }
    public SampleClass()
    { 

    }
    public SampleClass(string _name, byte _age, string _street, int _number)
    {
        Person p = new Person();
        p.Name = _name;
        p.Age = _age;
        Adress a = new Adress();
        a.Street = _street;
        a.Number = _number;
    }
}

我想得到这样的xml

<?xml version="1.0"?>
<SampleClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<Person>
    <Name></Name>
    <Age></Age>
</Person>
<Adress>
    <Street></Street>
    <HouseNumber></HouseNumber>
</Adress>
</SampleClass>

当我序列化这个 SimleClass 时:

When I serialize this SimleClass:

using (Stream str = new FileStream(@"C:/test.xml", FileMode.Create))
            {
                XmlSerializer serial = new XmlSerializer(typeof(SampleClass));
                SampleClass sClass = new SampleClass("John",15,"Street",34);
                serial.Serialize(str, sClass);
                label1.ForeColor = Color.Black;
                label1.Text = "Ok";
            }

它给了我 test.xml 文件,但该文件的内部是:

It's give me test.xml file but inside of that file is :

<?xml version="1.0"?>
 <SampleClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

我做错了什么?

感谢提前:)

推荐答案

你真正想要序列化的是:

What you really want serialize is this :

    Person p = new Person();
    p.Name = _name;
    p.Age = _age;
    Adress a = new Adress();

但是这些变量是局部的.为每个属性创建一个属性,并用可序列化的属性装饰它们.现在它可以工作了.

But these variables are local. Create a property of each one and decorate them with the serializable attribute too. Now it will work.

public SampleClass(string _name, byte _age, string _street, int _number)
{
    this.Person = new Person();
    Person p = this.Person;
    p.Name = _name;
    p.Age = _age;
    this.Adress = new Adress();
    Adress a = this.Adress;
    a.Street = _street;
    a.Number = _number;
}

[Serializable]
public Person Person { get; set; }
[Serializable]
public Adress Adress { get; set; }

顺便说一句:地址需要 2 天.

BTW: Address takes 2 d.

这篇关于在 C# 中序列化嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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