[ProtoContract]
public class ProtoTest
{
[ProtoMember(1)]
public List<string> Collecton { get; set; }
}
static void Main(string[] args)
{
ProtoTest test = new ProtoTest();
test.Collecton = new List<string>();
test.Collecton.Add("A");
test.Collecton.Add(null);
test.Collecton.Add("B");
test.Collecton.Add(null);
//This code works fine on Protobuf 1.0.0.282
//But throws exception on Protobuf 2.0.0.668
byte[] buffer = Serialize<ProtoTest>(test);
ProtoTest converted = Deserialize<ProtoTest>(buffer);
//In 1.0.0.282 converted.Collection is having 2 items excluded null values.
//In 2.0.0.668 Serialization fails with NullReference exception.
Console.Read();
}
[ProtoContract]
public abstract class NullableBase
{
public NullableBase()
{
}
[ProtoMember(1)]
public int? Value { get; set; }
}
[ProtoContract]
public class NullableChild:NullableBase
{
[ProtoMember(2)]
public string StrValue { get; set; }
}
[ProtoContract]
public class ProtoTest
{
[ProtoMember(1)]
public List<NullableBase> RefCollecton { get; set; }
}
static void Main(string[] args)
{
var nullableBaseType=ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(NullableBase), true);
nullableBaseType.AddSubType(100, typeof(NullableChild));
ProtoTest test = new ProtoTest();
test.RefCollecton = new List<NullableBase>();
test.RefCollecton.Add(new NullableChild() { StrValue = "A" });
test.RefCollecton.Add(new NullableChild() { StrValue = "B" });
test.RefCollecton.Add(null);
byte[] buffer = Serialize<ProtoTest>(test);
//For null values on reference type Protobuf is trying to create default instance.
//Here the type is NullBase and its an abstract class. Protobuf wont be able to create it and throwing exception.
//Why Protobuf creates default instance for null values.
ProtoTest converted = Deserialize<ProtoTest>(buffer);
Console.Read();
}
我们使用的是Protobuf 1.0.0.282,它在序列化时排除了参考类型和可空集合的空值。但是在V 2.0.0.668中,它对于可空类型和引用类型的行为方式不同。对于可空类型,它会在序列化时对空值抛出NullReferenceException。但是对于引用类型,它被序列化并且在反序列化时尝试为空值创建默认实例。
为什么他们删除了这个功能?这有什么特别的原因吗? 如果有任何好的理由,那么对于引用和可空类型集合它应该抛出nullreferenece异常吗?我们尝试过“SupportNull”https://code.google.com/p/protobuf-net/issues/detail?id=217的解决方案。