閱讀英文

共用方式為


如何使用 XmlSerializer 將物件還原序列化

當您還原序列化物件時,傳輸格式決定您會建立資料流或檔案物件。 決定傳輸格式後,您可視需要呼叫 SerializeDeserialize 方法。

還原序列化物件

  1. 使用要還原序列化的物件型別,建構 XmlSerializer

  2. 呼叫 Deserialize 方法以產生物件的複本。 在還原序列化時,您必須將所傳回物件轉換成原始的類型 (如下面的範例所示),其會從檔案將物件還原序列化 (雖然其也能從串流還原序列化)。

    C#
    // Construct an instance of the XmlSerializer with the type
    // of object that is being deserialized.
    var mySerializer = new XmlSerializer(typeof(MySerializableClass));
    // To read the file, create a FileStream.
    using var myFileStream = new FileStream("myFileName.xml", FileMode.Open);
    // Call the Deserialize method and cast to the object type.
    var myObject = (MySerializableClass)mySerializer.Deserialize(myFileStream);
    

另請參閱


其他資源

訓練

模組

儲存和擷取 JSON 檔案 - Training

瞭解如何使用 JsonSerializer 類別、JsonSerializerOptions 類別和數據傳輸物件,串行化和還原串行化 JavaScript 物件表示法 (JSON) 字串。