如何让Protobuf.NET忽略接口中返回IQueryable的方法?
问题与解决方法
问题重现
我定义了带Protobuf特性的接口INode,被类A、B继承:
[ProtoContract(ImplicitFields = ImplicitFields.None)] [ProtoInclude(1, typeof(A))] [ProtoInclude(2, typeof(B))] public interface INode { IQueryable BuildQueryable(); }
当序列化接口实例(比如INode ANode = new A();)时,Protobuf.NET报错:
InvalidOperationException: No serializer defined for type: System.Linq.IQueryable
需要让Protobuf.NET忽略BuildQueryable方法,不序列化它的返回值。
解决办法
直接在接口的BuildQueryable方法上标记[ProtoIgnore]特性,明确告诉Protobuf.NET跳过这个成员的序列化:
[ProtoContract(ImplicitFields = ImplicitFields.None)] [ProtoInclude(1, typeof(A))] [ProtoInclude(2, typeof(B))] public interface INode { [ProtoIgnore] IQueryable BuildQueryable(); }
这样Protobuf.NET就不会尝试处理这个方法的返回值,自然也就不会抛出IQueryable类型无法序列化的错误了。
如果后续发现继承类A或B里有相关的可序列化成员,也可以用同样的[ProtoIgnore]标记来排除,但直接在接口方法上标记是最直接有效的方式。
内容的提问来源于stack exchange,提问作者0xSingularity
相关产品推荐
相关产品推荐

