gpt4 book ai didi

.net - Protobuf如何设置Readonly属性

转载 作者:行者123 更新时间:2023-12-02 02:13:37 24 4
gpt4 key购买 nike

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

从我读过的其他 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com