簡體   English   中英

清單的C#4.0序列化<Customer>

[英]C# 4.0 Serialization of List<Customer>

在C#4.0中,我有一個稱為“客戶”的標准對象,它具有屬性和公共的空構造函數。

我需要將一個通用的List<Customer>序列化為XML,以便我可以保存它,然后加載它並反序列化它。

現在是否存在對此框架的支持,它比.NET 2.0中的支持更簡單?

XmlSerializer對此框架提供了支持,它幾乎沒有變化,但非常易於使用。

Linq具有XML支持,但是IMO的System.Xml.Serialization方式非常簡單。 編寫一個具有公共屬性的類,如果它很簡單,您甚至不需要對其進行注釋。 只需創建一個序列化器並在其上使用流,就可以完成。

這是我在商品庫中使用的內容:

public static string SerializeAsXml<TSource>(object element) where TSource : new()
{
    return SerializeAsXml<TSource>(element, new Type[] {});
}

public static string SerializeAsXml<TSource>(object element, Type[] extraTypes) where TSource : new()
{
    var serializer = new XmlSerializer(typeof(TSource), extraTypes);
    var output = new StringBuilder();
    using (StringWriter writer = new XmlStringWriter(output))
    {
        serializer.Serialize(writer, element);
    }
    return output.ToString();
}

public static TDestination Deserialize<TDestination>(string xmlPath) where TDestination : new()
{
    return Deserialize<TDestination>(xmlPath, new Type[] { });
}

public static TDestination Deserialize<TDestination>(string xmlPath, Type[] extraTypes) where TDestination : new()
{
    using (var fs = new FileStream(xmlPath, FileMode.Open))
    {
        var reader = XmlReader.Create(fs);
        var serializer = new XmlSerializer(typeof(TDestination), extraTypes);
        if (serializer.CanDeserialize(reader))
        {
            return (TDestination)serializer.Deserialize(reader);
        }
    }
    return default(TDestination);
}

不是超級簡單,但它的工作原理。 請注意,此操作僅從路徑反序列化,但是您可以輕松地將其更改為從字符串反序列化,只需FileStream

XmlStringWriter看起來像:

public class XmlStringWriter : StringWriter
{

    public XmlStringWriter(StringBuilder builder)
        : base(builder)
    {

    }

    public override Encoding Encoding
    {
        get { return Encoding.UTF8; }
    }

}

我只是在XML輸出上強制使用UTF8編碼。

序列化(將對象實例轉換為XML文檔):

// Assuming obj is an instance of an object
XmlSerializer ser = new XmlSerializer(obj.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, obj);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());

反序列化(將XML文檔轉換為對象實例):

//Assuming doc is an XML document containing a serialized object and objType is a System.Type set to the type of the object.
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(objType);
object obj = ser.Deserialize(reader);
// Then you just need to cast obj into whatever type it is eg:
MyClass myObj = (MyClass)obj;

您還可以嘗試msdn教程序列化(C#和Visual Basic)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM