[C#.NET] 序列化到MemoryStream

前面幾篇有講過如何序列化到檔案

[C#.NET] 利用 泛型方法 重構 反序列化

[C#.NET] 利用 泛型方法 重構 反序列化

[ADO.NET][C#.NET] 利用序列化+資料繫結 儲存表單參數

[C#.NET][Winform] 序列化表單 - 多國語言應用程式 / Form Serialize - Multiple Languages Application

這回來演練序列化到記憶體,以便讓其他程序直接呼叫,例如使用在Web Service的場景。


序列化:將物件序列化到MemoryStream後,再把它轉成字串取出來。

反序列化:則將字串轉成MemoryStream後,再反序列化

public class Serialize

{

    private Encoding _Encode = Encoding.UTF8;

    public Encoding Encode

    {

        get { return _Encode; }

        set { _Encode = value; }

    }

    public string ToXmlString(object Model)

    {

        using (MemoryStream ms = new MemoryStream())

        {

            XmlSerializer xs = new XmlSerializer(Model.GetType());

            xs.Serialize(ms, Model);

            return this.Encode.GetString(ms.ToArray());

        }

    }

    public T FromXmlString<T>(string XmlString)

    {

        using (MemoryStream ms = new MemoryStream(this.Encode.GetBytes(XmlString)))

        {

            XmlSerializer xs = new XmlSerializer(typeof(T));

            XmlTextWriter writer = new XmlTextWriter(ms, this.Encode);

            object obj = xs.Deserialize(ms);

            if (obj == null)

                return default(T);

            else

                return (T)obj;

        }

    }

}

接下來,建立單元測試來測試這兩個方法

序列化測試

/// <summary>

///A test for ToXmlString

///</summary>

[TestMethod()]

public void ToXmlStringTest()

{

    Serialize target = new Serialize();

    TestModel Model = new TestModel() { Name = "Yao", Age = 18 };

    string expected = "<?xml version=\"1.0\"?>\r\n<TestModel xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <Name>Yao</Name>\r\n  <Age>18</Age>\r\n</TestModel>";

    string actual;

    actual = target.ToXmlString(Model);

    Assert.AreEqual(expected, actual);

}

反序列化測試

/// <summary>

///A test for FromXmlString

///</summary>

public void FromXmlStringTestHelper<T>()

{

    Serialize target = new Serialize(); 

    string XmlString = "<?xml version=\"1.0\"?>\r\n<TestModel xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <Name>Yao</Name>\r\n  <Age>18</Age>\r\n</TestModel>";

    TestModel expected = new TestModel() { Name = "Yao", Age = 18 };

    TestModel actual;

    actual = target.FromXmlString<TestModel>(XmlString);

    Assert.AreEqual(actual.Name, expected.Name);

    Assert.AreEqual(actual.Age, expected.Age);

}



[TestMethod()]

public void FromXmlStringTest()

{

    FromXmlStringTestHelper<GenericParameterHelper>();

}
 

測試結果

image_thumb

你可能感兴趣的:(Stream)