为什么以下 protobuf-net 使用是非法的?
public interface IYObject
{
string X { get; }
}
public class YObject : IYObject
{
public string X { get; set; }
}
public class D
{
public IYObject Y { get; set; }
}
class Program
{
static void Main()
{
var m = RuntimeTypeModel.Default;
m.Add(typeof(D), true).Add("Y");
m.Add(typeof(IYObject), false).AddSubType(1, typeof(YObject)).Add("X");
var d = new D { Y = new YObject { X = "a" } };
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, d);
ms.Position = 0;
var d2 = Serializer.Deserialize<D>(ms);
Debug.Assert(d.Y.X == d2.Y.X);
}
}
}
当我尝试向 IYObject
添加子类型时,代码失败:
System.InvalidOperationException occurred
Message=Sub-types can only be adedd to non-sealed classes
Source=protobuf-net
StackTrace:
at ProtoBuf.Meta.MetaType.AddSubType(Int32 fieldNumber, Type derivedType)
InnerException:
public interface IYObject
{
string X { get; }
}
public class YObject : IYObject
{
public string X { get; set; }
}
public class D
{
public IYObject Y { get; set; }
}
class Program
{
static void Main()
{
var m = RuntimeTypeModel.Default;
m.Add(typeof(D), true).Add("Y");
m.Add(typeof(IYObject), false).AddSubType(1, typeof(YObject)).Add("X");
var d = new D { Y = new YObject { X = "a" } };
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, d);
ms.Position = 0;
var d2 = Serializer.Deserialize<D>(ms);
Debug.Assert(d.Y.X == d2.Y.X);
}
}
}
The code fails when I try to add a subtype to IYObject
:
System.InvalidOperationException occurred
Message=Sub-types can only be adedd to non-sealed classes
Source=protobuf-net
StackTrace:
at ProtoBuf.Meta.MetaType.AddSubType(Int32 fieldNumber, Type derivedType)
InnerException:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
大约 2 分钟前,这是非法的,因为接口不支持已知类型。
现在,这种用法是非法的,因为它
IYObject.X
无法安全地序列化,因为它没有setter。但是,只要我们将自己限制为可以合理序列化的接口成员或具体类型的成员,现在就已提交。使用属性或类型模型。 请在此处查看现在可用的方案(通过代码或下一次公开发布)。Before about 2 minutes ago, it was illegal because known-types weren't supported against interfaces.
Now, that usage is illegal because it can't safely serialize
IYObject.X
because it has no setter. However, as long as we restrict ourselves to interfaces members that can be sensible serialized, or members on the concrete type, this is now committed. Using either attributes or the type model. See here for the scenarios that are now available (via either code, or the next public drop).