码迷,mamicode.com
首页 > Windows程序 > 详细

c# 中的serializableAttribute

时间:2015-11-10 13:48:07      阅读:284      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!