繁体   English   中英

使用Protobuf-net序列化MultiValueDictionary(string,string)时出错

[英]Error serializing MultiValueDictionary(string,string) with Protobuf-net

我在我的项目(C#-VS2012-.net 4.5)中使用MultiValueDictionary(String,string) ,如果您希望每个键具有多个值,则这是一个很大的帮助,但是我无法使用protobuf.net序列化此对象。

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

有谁知道解决方法吗?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM