一次序列化两个词典

时间:2014-03-29 19:22:15

标签: c# serialization dictionary

我有两个类,如下所示,我在两个单独的Dictionaries中使用它们。我怎样才能Serialize这两个字典到一个文件?我可以在以下链接找到单个词典的序列化实现: Serialize a Dictionary<string, object>

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

[Serializable]
class Column
{
    public string Name { get; set; }
    public double Width { get; set; }
}

以下是我的词典:

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

var Dic2 = new Dictionary<string, Column>
{
    {"Column1", new Column{Name = "C1", Width = 10}},
    {"Column2", new Column{Name = "C2", Width = 5}},
};

这是我到目前为止编写的完整代码,但我得到了一个例外:

[Serializable]
public static class Building
{
    public static Dictionary<string, Beam> Beams;
    public static Dictionary<string, Column> Columns;
}

[Serializable]
public class Beam
{
    public string Name { get; set; }
}

[Serializable]
public class Column
{
    public string Name { get; set; }
}

static class Program
{
    static void Main()
    {

        Building.Beams.Add("Beam1", new Beam { Name = "B1"});
        Building.Columns.Add("Column1", new Column { Name = "C1" });

        Serialize();
    }

    static void Serialize()
    {

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

        var formatter = new BinaryFormatter();
        try
        {
            // I'm getting an excepting here:
            // 'Savef.Building' is a 'type' but is used like a 'variable'
            formatter.Serialize(fs, Building);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
        finally
        {
            fs.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

创建一个标有Serializable属性的类,其中包含这两个词典的实例:

[Serializable]
public class Building
{
    public static Building Instance = new Building();

    public readonly Dictionary<string, Beam> Beams = new Dictionary<string, Beam>();
    public readonly Dictionary<string, Column> Columns = new Dictionary<string, Column>();

    public static Dictionary<string, Beam> AllBeams
    {
        get { return Instance.Beams; }
    }
}

修改
用于避免例外的Singleton模式 在代码的其他部分使用Building.Instance来访问字典 的 EDIT2
引入了static属性:Building.AllBeams。你可以用它作为速记。