2014-03-29 61 views
2

我有一個簡單的類是這樣的:序列化詞典<字符串,對象>

class Beam 
{ 
    public string Name { get; set; } 
    public double Width { get; set; } 
    public double Height { get; set; } 
} 

而且我在Dictionary使用它作爲一個值:

var addresses = new Dictionary<string, Beam> 
{ 
    {"Beam1", new Beam{Name = "B1", Width = 10, Height = 10}}, 
    {"Beam2", new Beam{Name = "B2", Width = 5, Height = 5}} 
}; 

我怎樣才能SerializeDictionary?我能做到這一點時,Dictionary是象下面這樣:

Dictionary<string, string> 

但是,當我使用的是Object作爲它的價值我得到一個例外。

更新

var fs = new FileStream("DataFile.dat", FileMode.Create); 

// Construct a BinaryFormatter and use it to serialize the data to the stream. 
var formatter = new BinaryFormatter(); 
try 
{ 
    formatter.Serialize(fs, addresses); 
} 
catch (SerializationException e) 
{ 
    Console.WriteLine("Failed to serialize. Reason: " + e.Message); 
    throw; 
} 
finally 
{ 
    fs.Close(); 
} 

回答

4

您應該添加Serializable屬性的類Beam

[Serializable] 
class Beam 
{ 
    public string Name { get; set; } 
    public double Width { get; set; } 
    public double Height { get; set; } 
} 
+1

向類中添加屬性不會影響性能,但在這種情況下,使用反射來執行序列化。如果你有任何性能問題,通過實現'ISerializable'接口來創建你自己的串行器/解串器。 – Dmitry

+0

如果我有兩本字典呢?我能將這兩個序列化爲單個文件嗎?我會問這是一個新問題。 – Vahid

+0

是的。你可以創建一個* container *類(帶有'Serializable'屬性),包含這兩個'Dictionary',或者創建你自己的序列化器。 – Dmitry

相關問題