2
我有一個方法需要一個對象並將其轉換爲一個XML字符串。這很好,但我希望輸出XML包含對象屬性(string,int,double等)的數據類型。我搜索了高和低,但我似乎無法找到沒有編寫自定義序列化器的解決方案。.Net XmlSerializer輸出數據類型
任何幫助將不勝感激。
private static string ToXML<t>(t obj, bool indent = false)
{
System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
XmlSerializer xs = new XmlSerializer(typeof(t));
StringBuilder sbuilder = new StringBuilder();
var xmlws = new System.Xml.XmlWriterSettings() {OmitXmlDeclaration = true, Indent = indent};
ns.Add(string.Empty, string.Empty);
using (var writer = System.Xml.XmlWriter.Create(sbuilder, xmlws))
{
xs.Serialize(writer, obj, ns);
}
string result = sbuilder.ToString();
ns = null;
xs = null;
sbuilder = null;
xmlws = null;
return result;
}
此外,樣式建議 - 使用大寫字母或以大寫字母開頭的標識符將類型參數表示爲泛型。出於充分的理由,這是Microsoft推薦的做法;一目瞭然,您的代碼的讀者知道'T'是傳入您的方法的類型參數,而不是對象本身。 – RyanR
順便說一句,在C#中,您不需要將您的本地人分配給'null' .... –