2017-07-15 63 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); –