为了自由,幸福而不断奋斗,前行!!!

一笑看风云过....

博客园 首页 新随笔 联系 订阅 管理

//使用 XML 序列化将结构或对象转换成字符串
using System.Runtime.Serialization;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
  [Serializable]
  public struct MyStruct
  {
    public int i;
  }

  public class Program
  {
    static void Main(string[] args)
    {
      MyStruct myStruct = new MyStruct();
      myStruct.i = 123;

      XmlSerializer serializer = new XmlSerializer(typeof(MyStruct));

      // Struct To String
      MemoryStream stream = new MemoryStream();
      serializer.Serialize(stream, myStruct);
      stream.Seek(0, SeekOrigin.Begin);
      string s = Encoding.UTF8.GetString(stream.ToArray());
      Console.WriteLine(s);

      // String to Struct
      MemoryStream stream2 = new MemoryStream(Encoding.UTF8.GetBytes(s));
      MyStruct myStruct2 = (MyStruct)serializer.Deserialize(stream2);
      Console.WriteLine(myStruct2.i);
    }
  }
}

posted on 2008-07-15 10:36  YAO'STAR  阅读(239)  评论(0编辑  收藏  举报