我正在编写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 >();
}
}