Created
June 13, 2013 11:40
-
-
Save doggy8088/5773055 to your computer and use it in GitHub Desktop.
當試圖序列化系統內建的型別之後,若試圖反序列化為 object 型別一定會引發錯誤,請問在 Main() 方法不修改的情況下,如何讓這段程式正常運作?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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