当前位置:   article > 正文

c# 中的serializableAttribute

c# serializableattribute
using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

// A test object that needs to be serialized.
[System.Serializable]        
public class TestSimpleObject  {
    
    public int member1;
    public string member2;
    public string member3;
    public double member4;
    
    // A field that is not serialized.
    [System.NonSerialized] public string member5; 
    
    public TestSimpleObject() {
        
        member1 = 11;
        member2 = "hello";
        member3 = "hello";
        member4 = 3.14159265;
        member5 = "hello world!";
    }
    
    
    public void Print() {
        
        Debug.Log("member1 = " + member1);
        Debug.Log("member2 = " + member2);
        Debug.Log("member3 = " + member3);
        Debug.Log("member4 = " + member4);
        Debug.Log("member5 = " + member5);
    }
}

[ExecuteInEditMode]
public class TestSerializerable : MonoBehaviour 
{

    // Use this for initialization
    void Start () 
    {
        TestSerializerable.Main();
    }

    public static void Main()  
    {
            
            //Creates a new TestSimpleObject object.
            TestSimpleObject obj = new TestSimpleObject();
            
            Debug.Log("Before serialization the object contains: ");
            obj.Print();
            
            //Opens a file and serializes the object into it in binary format.
            Stream stream = File.Open("data.xml", FileMode.Create);
            //SoapFormatter formatter = new SoapFormatter();
            
            BinaryFormatter formatter = new BinaryFormatter();
            
            formatter.Serialize(stream, obj);
            stream.Close();
            
            //Empties obj.
            obj = null;
            
            //Opens file "data.xml" and deserializes the object from it.
            stream = File.Open("data.xml", FileMode.Open);
            //formatter = new SoapFormatter();
            
            formatter = new BinaryFormatter();
            
            obj = (TestSimpleObject)formatter.Deserialize(stream);
            stream.Close();
            
            Debug.Log("After deserialization the object contains: ");
            obj.Print();
    }
}

以上代码 在unity环境下运行

 

转载于:https://www.cnblogs.com/bysdtd/p/4952516.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/111885?site
推荐阅读
相关标签
  

闽ICP备14008679号