我有一个接口和一个实现,都带有 [ProtoContract]。有一个属性,在界面上是只读的。当我尝试反序列化声明为接口的属性时,Protobuf 给了我这个错误:
System.InvalidOperationException: Cannot apply changes to property IFoo.Id
这是我正在测试的代码:
public void Main()
{
using (var ms = new MemoryStream())
{
var x = new HasFoo {TheFoo = new Foo(1)};
Serializer.Serialize(ms, x);
ms.Position = 0;
var clone = Serializer.Deserialize<HasFoo>(ms);
Assert.AreEqual(1, clone.TheFoo.Id);
}
}
[ProtoContract, ProtoInclude(100, typeof(Foo))]
public interface IFoo
{
[ProtoMember(1)]
long Id { get; }
}
[ProtoContract]
public class Foo : IFoo
{
[ProtoMember(1)]
public long Id { get; private set; }
public Foo() { }
public Foo(long id)
{
Id = id;
}
}
[ProtoContract]
public class HasFoo
{
[ProtoMember(1)]
public IFoo TheFoo { get; set; }
}
我宁愿不在接口上声明 setter,而且我希望尽可能保持TheFoo
声明的属性IFoo
。有什么方法可以让它起作用吗?我正在使用 protobuf-net v2。