.net - Protobuf如何设置Readonly属性

标签 .net protobuf-net

我很好奇这实际上是如何工作的,因为我只是想确保我没有弄错我的测试成功这一事实。

从我读过的其他 stackoverflow 问题来看,protobuf 无法设置只读属性。但它似乎做得很好。

我有以下类(class)(经过修剪以进行演示)

<
ProtoContract()
> _
Public Class WebOrder
    Implements IWebOrder

   Friend Sub New()
      MyBase.New()
      mItems = New Ordered.StockItemsCollection
   end sub 

   Private mItems As Ordered.StockItemsCollection
    <ProtoMember(4)>
    Public ReadOnly Property Items As Ordered.StockItemsCollection
        Get
            Return mItems
        End Get
    End Property

    Private ReadOnly Property COMItems As Ordered.StockItemsCollection Implements IWebOrder.Items
        Get
            Return mItems
        End Get
    End Property
end class

当我用下面的代码测试它是成功的。

Dim si As New WebConnector.Ordered.StockItem With {.ItemType = WebConnector.StockItemType.Instruction, 
                    .Description = "test", .Quantity = 5}

activeOrder.Items.Add(si)

Using ms As New MemoryStream
    ProtoBuf.Serializer.Serialize(Of WebConnector.WebOrder)(ms, activeOrder)
    ms.Seek(0, SeekOrigin.Begin)
    ch = ProtoBuf.Serializer.Deserialize(Of WebConnector.WebOrder)(ms)
End Using

For Each si In ch.Items
    Debug.Print(si.ItemType.ToString & " --- " & si.Description & " --- x" & si.Quantity)
Next

结果:

说明 --- 测试 --- x5

protobuf 是进入我的属性并找到支持字段并设置它还是只是 .Add 到集合或 StockItems?

最佳答案

对于列表,它不需要是可读写的;基本上,如果它是只读的,它只使用 .Add。如果它是可读写的,那么它还会做一个额外的“它是空的吗?如果是,创建一个新的列表实例,并调用 setter”。这意味着惰性代码可以工作,即(使用 c# 示例)

[ProtoMember(12)]
public List<Foo> Items {get;set;}

但是,我的个人偏好列表是只读的,就像您的示例一样。

Is protobuf reaching Into my property and finding the backing field and setting it or is it just .Add to the collection or StockItems?

后者。它从不尝试解析属性中的字段。如果您显式标记字段以进行序列化,它将对它们起作用 - 但它不会在没有被告知的情况下这样做。

关于.net - Protobuf如何设置Readonly属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11643278/

相关文章:

c# - protobuf-net:属性与字段

.net - ORM For .Net ON Oracle

c# - 洋葱架构中的典型层是什么?

c# - 将多个组合框绑定(bind)到 1 个列表<>

c# - 异步/等待异常处理

protobuf-net - 使用 protobuf-net 时将空字符串反序列化为空字符串

c# - 如何使用 ProtoBuf-Net 序列化继承类

c# - ProtoBuf 在反序列化期间损坏字节数组(添加了额外的 0)

c# - Linq to XML - 解析 DateTime 时检查 null 元素

c# - 将对象列表作为单个响应进行流式传输,并提供进度报告