【问题标题】:Error serializing MultiValueDictionary(string,string) with Protobuf-net使用 Protobuf-net 序列化 MultiValueDictionary(string,string) 时出错
【发布时间】:2015-08-01 07:35:53
【问题描述】:

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

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

有人知道解决方法吗?

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

System.InvalidOperationException:无法解析合适的添加 System.Collections.Generic.IReadOnlyCollection 的方法

【问题讨论】:

    标签: c# serialization protobuf-net multi-value-dictionary


    【解决方案1】:

    你真的需要字典吗? 如果您的字典中的项目少于 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;
    

    【讨论】:

    • 感谢@KlausFischer,我的字典包含超过 150 万个元素,我使用这种类型是因为它的检索时间很快。我用过很多其他类型,MultiValueDictionary 是迄今为止最快的!
    猜你喜欢
    • 2021-10-20
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多