簡體   English   中英

使用DataContract Collection反序列化 <Class> 派生類

[英]Deserializing with DataContract Collection<Class> to derived Class

標題有點令人困惑,希望有人可能知道我的問題更合適。

我正在嘗試創建一個從Collection<Classname>派生的類,以實現一種簡單的方法來保存和加載配置文件。 寫入文件沒有問題,但是我無法實現解串功能。 我不確定如何將反序列化的內容分配回我的實例。

當前方法:

[DataContract(Name = "Configurations", Namespace = "")]
public class Configurations : Collection<Configuration>
{
    internal void SerializeToBinaryFile(string path)
    {
        Helper.DumpObjectToBinaryFile(this, path);
    }

    internal void DeserializeFromBinaryFile(string path)
    {
       // Getting Error:
       // This expression can not be used as an assignment target
       this = Helper.GetObjectFromBinaryFile<Collection<Configuration>>(path);
    }
}

我對this.Add([Configuration])很熟悉,但這僅是插入一個項目的機會。 我考慮過foreach(Configuration c in temporaryObject使用foreach(Configuration c in temporaryObject並逐一添加它們,但這不是最佳解決方案。

感謝您的提示!

編輯1:

我添加了foreach迭代以添加配置

    internal void DeserializeFromBinaryFile(string path)
    {
        foreach (var c in Helper.GetObjectFromBinaryFile<Collection<Configuration>>(path))
        {
            Add(c);
        }
    }

這似乎很好。 有人知道更好的模式嗎?

無論您要進行反序列化還是其他操作,都不能將新的類實例分配給“ this”。 下面的代碼僅使用新的構造函數,也不起作用。 基本上,那時您在內存中確實有兩個不同的類實例。

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public void CreatePoint(int x, int y)
    {
        // Doesn't work either
        this = new Point();
    }
}

您必須在類的主體之外執行此操作,因此要使用靜態反序列化方法:

[DataContract(Name = "Configurations", Namespace = "")]
public class Configurations : Collection<Configuration>
{
    internal void SerializeToBinaryFile(string path)
    {
        Helper.DumpObjectToBinaryFile(this, path);
    }

    internal static Configurations DeserializeFromBinaryFile(string path)
    {
        return Helper.GetObjectFromBinaryFile<Collection<Configuration>>(path);
    }
}

暫無
暫無

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

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