我正在編寫C#
與protobuf-net
編寫的項目。我有代碼序列化/反序列化Dictionary<MyClass1, MyClass2>
文件。另外,我有一個帶有序列化數據的文件。當我嘗試反序列化它時,我收到一個異常key
不能是null
。我不明白怎麼可能,因爲Dictionary
不允許null
,它看起來像我不能序列化這樣的字典。我認爲該文件已損壞,但我不確定。我試圖調試它,看起來像幾個鍵和值正確反序列化,但在反序列化過程中,null
鍵發生,我看到異常。我試圖使用代理ProductName
提到here但它沒有幫助。Protobuf詞典diserialization引發null key異常
如何反序列化此文件? 可能有反序列化某些對象的方法,而不是null
對於ProductName
?
例外:
System.ArgumentNullException:值不能爲空。 參數名稱:在System.Collections.Generic.Dictionary
2.Insert(TKey key, TValue value, Boolean add) at System.Collections.Generic.Dictionary
2.System.Collections.Generic.ICollection鍵 >。新增(KeyValuePair`2 keyValuePair) 在proto_10(對象,ProtoReader) 在ProtoBuf.Meta.TypeModel.DeserializeCore (ProtoReader reader,Type type,Object value,Boolean noAutoCreate)in ProtoBuf.Meta.Type.Model.Deserialize(Stream source,Object value)在c:\ Dev \ protobuf-net \ protobuf-net \ Meta \ TypeModel.cs中:行704 ,Type type,SerializationContext context)在c:\ Dev \ protobuf-net \ protobuf-net \ Meta \ TypeModel.cs中:第588行 位於ProtoBuf.Serializer.Deserialize [T](Stream source)in c:\ Dev \ protobuf -net \ protobuf-net \ Serializer.cs:line 77
代碼:
[ DataContract ]
public sealed class ProductName
{
[ DataMember(Order = 1) ]
public string Name { get; private set; }
public static readonly ProductName Undefined = Create("Unknown");
private ProductName()
{
}
private ProductName(string Name)
{
this.Name = Name.Trim();
}
public static ProductName Create(string Name)
{
Condition.Requires(Name, "Name").IsNotNullOrEmpty();
return new ProductName(Name);
}
public static ProductName TryCreate(string Name)
{
return Name.IsValidName() ? new ProductName(Name) : null;
}
public override string ToString()
{
return this.Name;
}
public override int GetHashCode()
{
var stableHashCodeIgnoringCase = this.Name.GetStableHashCodeIgnoringCase();
return stableHashCodeIgnoringCase;
}
#region Equality members
public bool Equals(ProductName other)
{
if(ReferenceEquals(null, other))
return false;
if(ReferenceEquals(this, other))
return true;
return string.Equals(this.Name, other.Name, StringComparison.InvariantCultureIgnoreCase);
}
public override bool Equals(object obj)
{
if(ReferenceEquals(null, obj))
return false;
if(ReferenceEquals(this, obj))
return true;
if(obj.GetType() != this.GetType())
return false;
return this.Equals((ProductName)obj);
}
#endregion
}
[ DataContract ]
public class ProductNameIndex
{
[ DataMember(Order = 1) ]
public IDictionary< ProductName, ProductId > Products{ get; private set; }
public ProductNameIndex()
{
this.Products = new Dictionary< ProductName, ProductId >();
}
}