2

我在我的项目(C# - VS2012 - .net 4.5)中使用MultiValueDictionary(String,string),如果您想为每个键设置多个值,这将很有帮助,但我无法使用 protobuf.net 序列化此对象.

我已经用 Protobuf 轻松快速地序列化了Dictionary(string,string)并且MultiValueDictionary继承自该泛型类型;因此,从逻辑上讲,使用相同的协议对其进行序列化应该没有问题。

有人知道解决方法吗?

这是我执行代码时的错误消息:

System.InvalidOperationException:无法为 System.Collections.Generic.IReadOnlyCollection 解析合适的 Add 方法

4

1 回答 1

0

你真的需要字典吗?如果您的字典中的项目少于 10000 个,您还可以使用修改后的数据类型列表。

    public class YourDataType
    {
        public string Key;

        public string Value1;

        public string Value2;

        // add some various data here...
    }

    public class YourDataTypeCollection : List<YourDataType>
    {
        public YourDataType this[string key]
        {
            get
            {
                return this.FirstOrDefault(o => o.Key == key);
            }
            set
            {
                YourDataType old = this[key];
                if (old != null)
                {
                    int index = this.IndexOf(old);
                    this.RemoveAt(index);
                    this.Insert(index, value);
                }
                else
                {
                    this.Add(old);
                }
            }
        }
    }

使用这样的列表:

    YourDataTypeCollection data = new YourDataTypeCollection();

    // add some values like this:
    data.Add(new YourDataType() { Key = "key", Value1 = "foo", Value2 = "bar" });

    // or like this:
    data["key2"] = new YourDataType() { Key = "key2", Value1 = "hello", Value2 = "world" };
    // or implement your own method to adding data in the YourDataTypeCollection class

    XmlSerializer xser = new XmlSerializer(typeof(YourDataTypeCollection));

    // to export data
    using (FileStream fs = File.Create("YourFile.xml"))
    {
        xser.Serialize(fs, data);
    }

    // to import data
    using (FileStream fs = File.Open("YourFile.xml", FileMode.Open))
    {
        data = (YourDataTypeCollection)xser.Deserialize(fs);
    }

    string value1 = data["key"].Value1;
于 2015-08-01T08:26:42.870 回答