首页 > Windows开发 > 详细

c# 中的serializableAttribute

时间:2015-11-10 13:48:05      阅读:220      评论:0      收藏:0      [点我收藏+]
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环境下运行

技术分享

 

c# 中的serializableAttribute

原文:http://www.cnblogs.com/bysdtd/p/4952516.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!