我想編寫一個C#客戶端通過protobuf網發送一個字符串到TCP服務器(實施)。但是,當我嘗試使用protobuf-net序列化字符串時,我得到一個TypeInitializerException
「'Singleton'的類型初始值設定項引發了一個異常。」錯誤序列化使用protobuf網C#字符串
下面是代碼:
public static void TelnetConnect(string host, int port) {
...
Message msg = new Message("This is a test.");
byte[] sentbytes = msg.Serialize();
...
}
[ProtoContract]
public abstract class MessageI {
public byte[] Serialize() {
byte[] result;
using (var stream = new MemoryStream()) {
Serializer.Serialize(stream, this); //THIS LINE THROWS EXCEPTION
result = stream.ToArray();
}
return result;
}
}
[ProtoContract]
public class Message : MessageI {
[ProtoMember(1)]
public string str { get; set; }
public Message(string s) {
this.str = s;
}
}
我已經嘗試了一些由本網站和其他人建議的方法,但沒有成功。我在Visual Studio 2010上使用C#。
謝謝,我非常感謝你的幫助。
UPDATE:堆棧跟蹤爲:
at ProtoBuf.Meta.RuntimeTypeModel.get_Default()
at ProtoBuf.Serializer.Serialize[T](Stream destination, T instance)
at PingNorbertServer.MessageI.Serialize() in C:\Users\RS88517\Documents\Visual Studio 2010\Projects\PingNorbertServer\PingNorbertServer\NorbertClient.cs:line 37
at PingNorbertServer.NorbertClient.TelnetConnect(String host, Int32 port) in C:\Users\RS88517\Documents\Visual Studio 2010\Projects\PingNorbertServer\PingNorbertServer\NorbertClient.cs:line 23
at PingNorbertServer.NorbertClient.Main(String[] args) in C:\Users\RS88517\Documents\Visual Studio 2010\Projects\PingNorbertServer\PingNorbertServer\NorbertClient.cs:line 14
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
我不知道什麼是Singleton類,但它可能是MemoryStream,Serializer或Message。 –
這個異常通常發生在調用靜態構造函數時會引發錯誤。您的調試器不會自動將您帶入靜態構造函數(可能爲「Singleton」),因此您需要查看堆棧跟蹤以找到真正的錯誤 – jcharlesworthuk
謝謝,1.儘管如此,錯誤是什麼? –