Skip to content

Instantly share code, notes, and snippets.

@doggy8088
Created June 13, 2013 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save doggy8088/5773055 to your computer and use it in GitHub Desktop.
Save doggy8088/5773055 to your computer and use it in GitHub Desktop.
當試圖序列化系統內建的型別之後,若試圖反序列化為 object 型別一定會引發錯誤,請問在 Main() 方法不修改的情況下,如何讓這段程式正常運作?
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "1234";
string xml = SiteHelper.Serialize(s);
object obj = SiteHelper.Deserialize<object>(xml);
}
}
public static class SiteHelper
{
public static string Serialize(object o)
{
XmlSerializer ser = new XmlSerializer(o.GetType());
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
ser.Serialize(writer, o);
return sb.ToString();
}
public static T Deserialize<T>(string s)
{
MemoryStream ms = new MemoryStream(Encoding.GetEncoding("UTF-16").GetBytes(s));
XmlTextReader reader = new XmlTextReader(ms);
reader.Normalization = false;
XmlSerializer ser = new XmlSerializer(typeof(T));
object obj = ser.Deserialize(reader); // Exception happen!!
return (T)obj;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment