【Unity数据持久化】C#中Xml的反序列化

把序列化的xml文件读取到内存中的类对象中
就称为反序列化

关键字:
1.using和 StreamReader
2.XmlSerializer.Deserialize()反序列化方法

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;
public class Lesson2 : MonoBehaviour
{
    
    
    void Start()
    {
    
    
        string path = Application.persistentDataPath + "/Lesson1Test.xml";
        if (File.Exists(path))
        {
    
    
            //读取文件
            using (StreamReader reader = new StreamReader(path))
            {
    
    
                //要翻译谁? 翻译上节中的数据结构类型
                XmlSerializer s = new XmlSerializer(typeof(Lesson1Test));
                //调用反序列化方法,把文件流传入
                //返回值是万物之父object,只需把它as成对应类型即可
                //如此就把Lesson1Test.xml的值先加载到内存中,再读取到新new的对象lt中
                Lesson1Test lt = s.Deserialize(reader) as Lesson1Test;
            }
        }
    }
}

此处有坑
序列化时ListInt明明只有4个值
却读出来8个
在这里插入图片描述
因为在被序列化的数据结构类中的List初始化时就赋了值

public List<int> listInt = new List<int> {
    
     9, 8, 7, 6 };

List不会覆盖之前的值,而是往里Add值
也就是说,如果有默认值,在反序列化时 不会先清空 而是继续往后面Add值
由此得知,如果要对List序列化和反序列化
建议List不要在声明时就在内部赋值,而是在外部赋值

猜你喜欢

转载自blog.csdn.net/SEA_0825/article/details/127200831