//使用 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);
}
}
}