TCPソケットがあり、ProtoBufを使用してオブジェクトを送受信したいと思います。しかし、私はこのエラーを受け取ります:
スローされた例外:protobuf-net.dllの「System.InvalidOperationException」
タイプは予期されておらず、コントラクトを推測することはできません:Server.Packet.IMsg
私のインターフェース:
public interface IMsg { }
送受信したいオブジェクトの1つ:
[ProtoContract]
public class PacketPerson : IMsg
{
[ProtoMember(1)]
public string Name{ get; set; }
[ProtoMember(2)]
public string Country { get; set; }
}
バッファがいっぱいになった後、ソケットが逆シリアル化しようとしています。
IMsg msg = Serialization.Desirialize(SocketMemoryStream);
望ましい:
public static IMsg Desirialize(MemoryStream ms) // socket buffer
{
ms.Position = 0;
return Serializer.Deserialize<IMsg>(ms);
}
はい。ただし、マルチオブジェクトを送信し、「Type type = packet.GetType();」を使用してそれらを識別したいと思います。次に、Ifステートメント「if(type == typeof(PacketPerson))」を使用します
私の提案(著者として話す):
[ProtoContract]
[ProtoInclude(1, typeof(PacketPerson))]
// future additional message types go here
class SomeMessageBase {}
[ProtoContract]
class PacketPerson : SomeMessageBase
{
[ProtoMember(1)]
public string Name{ get; set; }
[ProtoMember(2)]
public string Country { get; set; }
}
および逆シリアル化/シリアル化<SomeMessageBase>
。ライブラリは、ここですべての継承を正しい方法で処理します。舞台裏では、これは(.proto用語で)同様に実装されます:
message SomeMessageBase {
oneof ActualType {
PacketPerson = 1;
// ...
}
}
message PacketPerson {
string Name = 1;
string Country = 2;
}
実行時に実際の型を決定するために、ポリモーフィズムまたは型テストのいずれかを使用できるようになりました。新しいswitch
構文は特に便利です。
SomeMessageBase obj = WhateverDeserialize();
switch(obj)
{
case PacketPerson pp:
// do something person-specific with pp
break;
case ...:
// etc
break;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加