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 に答える