我在我的项目中使用MultiValueDictionary(String,string)(C# - VS2012 - .net 4.5),如果你想为每个键设置多个值,这是一个很好的帮助,但是我不能序列化这个对象与protobuf.net。
我已经使用Protobuf轻松快速地序列化 Dictionary(字符串,字符串),并且 MultiValueDictionary 继承了该泛型类型;所以,逻辑上应该没有问题使用相同的协议序列化它。
有人知道解决方法吗?
这是我执行代码时的错误消息:
System.InvalidOperationException:无法解析合适的Add System.Collections.Generic.IReadOnlyCollection
的方法
答案 0 :(得分: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;