简体   繁体   中英

How do you serialize and deserialize an enum?

I am trying to create an enum with commands for motor control in VB.NET. I want to set the command on one computer, serialize it, send it to another computer over a TCP connection, deserialize, and interpret the command. I know how to use the TCP connection, but I'm missing conceptual knowledge about the enum. I am using Protobuf-net to serialize and have the following description of commands.

Public Class RemoteControl

   <ProtoContract>
    Public Class Command

       <ProtoContract>
       Enum CommandAction
        <ProtoMember(2)>
        HOME_MOTOR

        <ProtoMember(1)>
        MOVE_ABS
        End Enum
   End Class
 End Class

My question is, how do I set the instance of a RemoteControl object to the action I want? I know enums use integers, so to send a MOVE_ABS (which has a tag of 1), I tried

 Dim myAction As New RemoteControl
 myAction.Command.CommandAction = 1

This returned an error saying "CommandAction is a type and cannot be used as an expression".

Also, once I do manage to figure out how to send this command, how would I interpret it on the other computer? Would the deserialized value of something like RemoteControl.Command.CommandAction be equal to 1 if the command sent was MOVE_ABS ?

As usual, I spent days on this then figured it out immediately after making this post.

What I ended up doing was:

SERVER SIDE
Dim realProto As New RemoteControl.Command.CommandAction
realProto = RemoteControl.Command.CommandAction.MOVE_ABS
ProtoBuf.Serializer.SerializeWithLengthPrefix(myStream, realProto, ProtoBuf.PrefixStyle.Fixed32)


CLIENT SIDE
Dim readProto As New RemoteControl.Command.CommandAction
readProto = Protobuf.Serializer.DeserializeWithLengthPrefix(Of RemoteControl.Command.CommandAction)(myStream, Protobuf.PrefixStyle.Fixed32)

This then sets readProto as a RemoteControl.Command.CommandAction whose value is an integer corresponding to the action tag, or I can do readProto.ToString to view the name of the action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM