2017-07-15 157 views
-1

我被困在這個問題,我一直在尋找答案的任何地方,但沒有找到適合我的問題的東西。我想序列化對象並將其保存到二進制文件中,並將其作爲列表,因爲它將返回多行記錄。序列化對象然後反序列化爲列表<object> C#

所以,這是我的課

[Serializable] 
public class DTOMultiConfig 
{ 
    public string Key { get; set; } 
    public string KeyValue { get; set; } 
} 

[Serializable] 
public class DTOMultiConfigs : List<DTOMultiConfig> 
{ 
    public void Dispose() 
    { 
    } 
} 

,我用這些方法我在網上找到。這是我如何序列化我的對象,這部分工作

public void Editor_Config(DTOMultiConfig dto) 
{ 
    if (dto.ID == 0)//new 
    { 
     dto.ID = 0; 
     WriteToBinaryFile(BinPath, dto, true); 
    } 
    else//edit 
    { 
    } 
} 

public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false) 
{ 
    using (Stream stream = System.IO.File.Open(filePath, append ? FileMode.Append : FileMode.Create)) 
    { 
     var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
     binaryFormatter.Serialize(stream, objectToWrite); 
    } 
} 

這是我如何使用deserialize方法,我不知道,我敢肯定,我做了錯誤的方式,因爲它不工作所有。 ReadFromBinaryFile在「返回」聲明之前停止工作。

public PartialViewResult ShowListOfConfigs() 
{ 
    List<DTOMultiConfig> dto = new List<DTOMultiConfig>(); 

    //DESERIALIZE 

    dto = ReadFromBinaryFile<List<DTOMultiConfig>>(BinPath); 
    return PartialView("_ListOfConfigs", dto); 
} 

public static T ReadFromBinaryFile<T>(string filePath) 
{ 
    using (Stream stream = System.IO.File.Open(filePath, FileMode.Open)) 
    { 
     var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
     return (T)binaryFormatter.Deserialize(stream); 
    } 
} 

任何答案與一些解釋將不勝感激。

+0

你得到的例外是什麼?我懷疑你的問題是你寫了一個DTOMultiConfig實例,但是試圖讀取一個List ,因爲你的類型的單個實例的二進制表示與列表的二進制表示不同,所以它不能工作。 – dnickless

+0

你好,謝謝你的迴應,我得到了這個exeption {「無法將類型爲'MVCHowTo.Models.DTOMultiConfig'的對象轉換爲類型'System.Collections.Generic.List'1 [MVCHowTo.Models.DTOMultiConfig]'。 「} –

+0

因此,在寫入二進制文件時,是否應該讓我的dtoMultiConfig成爲一個列表?因爲我一次只寫1條記錄,所以 –

回答

0

讓我試着解釋一下。想象一下,你沒有使用二進制序列化器,而是使用XML序列化器。在這種情況下,你會寫什麼看起來有點像這樣:

<DTOMultiConfig> 
    <Key>SomeKey</Key> 
    <Value>SomeValue</Value> 
</DTOMultiConfig> 

現在,當你讀您的數據備份,您正試圖您的單一實例反序列化到其中,但是,將需要一個列表看起來有點類似於此:

<ListOfDTOMultiConfigs> 
    <DTOMultiConfig> 
    <Key>SomeKey</Key> 
    <Value>SomeValue</Value> 
    </DTOMultiConfig> 
    [...potentially more elements here...] 
</ListOfDTOMultiConfigs> 

這根本無法工作。在二進制世界中,文件中的實際數據看起來不同。然而,同樣的問題仍然存在:除非它們的結構完全相同,否則不能寫出一種類型並讀取另一種類型。

爲了處理你的具體情況,你可以讀回一個單一的元素,然後把它放在一個列表中,如果你需要列表。或者你可以用一個單獨的元素寫一個列表到你的文件中,然後用你的上面的代碼讀回這個列表。

編輯:

在您的評論你上面說,你會想到寫一個元素兩次,該文件應該給你一個列表。回到我上面的例子,寫一個單一的元素兩次會給你:

<DTOMultiConfig> 
    <Key>SomeKey</Key> 
    <Value>SomeValue</Value> 
</DTOMultiConfig> 
<DTOMultiConfig> 
    <Key>SomeKey</Key> 
    <Value>SomeValue</Value> 
</DTOMultiConfig> 

如果你比較這對我的例子爲列表的表現上面,你會看到,他們是不相同的,因此不能可互換使用。

+0

好的,我會盡量將它寫成一個列表,我會讓你知道的。謝謝! –

+0

嗯,我實際上在文件上寫了一個兩次...但它只返回一條記錄 –

+0

這是我的更新代碼:List _dto = new List (); _dto.Add(dto); WriteToBinaryFile(BinPath,_dto,true); –