您的位置:首页 > 其它

StructToString / StringToStruct

2008-07-15 10:36 190 查看
//使用 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);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: