最近工作上需要做一些跟XML有關的東西,所以先準備些工具,一開始也沒多想就寫了將XML轉成Object的方法,但是使用上有點不漂亮。
static object XmlToObj(XDocument xml, Type objType)
{
object obj;
try
{
XmlSerializer serializer = new XmlSerializer(objType);
using (TextReader reader = new StringReader(xml.ToString()))
{
obj = serializer.Deserialize(reader);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
return obj;
}
Using above XmlToObj, it need to cast it first, the code isn't feel so beauty, so I decide rewrite it to generic method.
使用上面的XmlToObj,會需要做轉型才能使用,code感覺不是很美,所以我決定改寫成泛型的方式。
var result = (PurchaseOrder)XmlToObj(doc, typeof(PurchaseOrder));
After rewrite to generic method, it look like it.
轉成泛型的方式後,變成如下。
static T XmlToGeneric(XDocument xml)
{
T obj;
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xml.ToString()))
{
obj = (T)serializer.Deserialize(reader);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
obj = default(T);
}
return obj;
}
It's more beauty on using.
使用上就漂亮了很多
var result = XmlToGeneric(doc);
Compare both method, the generic method looks like more elegant.
比較兩者,使用泛型的方法看來簡潔許多。
//to generic
var result1 = XmlToGeneric(doc);
//to object
var result2 = (PurchaseOrder)XmlToObj(doc, typeof(PurchaseOrder));
No comments:
Post a Comment