2

I'm trying to move an existing code to use ProtoBuf-Net. Some classes have DataContract but DataMembers has no order, this results with ignoring these properties instead of serializing them.

Is there a way to tell ProtoBuf-Net to serialize only classes that are marked with [ProtoContract] and throw exception when trying to serialize classes with [XmlType] or [DataContract]? If it's possible, will the other system classes (for example System.String) be serialized correctly using GPB?

Thanks.

4

1 に答える 1

2

Fair question; it isn't a scenario that has come up before, but it is a fair-enough scenario, and is pretty easily solved, thankfully... I've added AutoAddProtoContractTypesOnly to RuntimeTypeModel in r567. If you are using the v1-style Serializer.Serialize(...) methods, then you can apply this via:

RuntimeTypeModel.Default.AutoAddProtoContractTypesOnly = true;

(all the Serializer.* methods are mapped to the RuntimeTypeModel.Default model instance)

Here's my now-passing test:

[Test]
public void ExecuteWithoutAutoAddProtoContractTypesOnlyShouldWork()
{
    var model = TypeModel.Create();
    Assert.IsInstanceOfType(typeof(Foo), model.DeepClone(new Foo()));
}
[Test, ExpectedException(typeof(InvalidOperationException),
    ExpectedMessage = "Type is not expected, and no contract can be inferred: Examples.Issues.SO11871726+Foo")]
public void ExecuteWithAutoAddProtoContractTypesOnlyShouldFail()
{
    var model = TypeModel.Create();
    model.AutoAddProtoContractTypesOnly = true;
    Assert.IsInstanceOfType(typeof(Foo), model.DeepClone(new Foo()));
}

[DataContract]
public class Foo { }
于 2012-08-08T20:37:19.630 に答える