C#反序列化类型向下转换为xml

时间:2017-04-25 20:24:53

标签: c# xml serialization mono xml-serialization

Execution Result

反序列化对象后,C#会输出正确的对象类型,但不允许我向下转换它。任何人都可以解释原因吗?

该项目涉及两个程序(服务器和客户端),试图通过TCP连接序列化c#对象。

代码在mono 4.5下的linux上运行,它的目的是运行Unity脚本。

我也尝试过二进制格式化程序,结果相同

我在这里引用两端的代码:

  

        private void   listenerMethod ()
        {
            Console.WriteLine ("Listening to packets");
            try {
                while (true){
                    System.Object o = this.xmlSerializerIn.Deserialize(this.stream);
                    Console.WriteLine("Object string: "+o.ToString());
                    try{
                        Game.Message.DebugMsgGame debug= (Game.Message.DebugMsgGame) o;
                        Console.WriteLine(debug);
                    }catch (InvalidCastException e){
                        Console.WriteLine (e);
                        Console.WriteLine(o.GetType());
                    }
                    try{
                        Game.Message.IGameMessage gm= (Game.Message.IGameMessage) o;
                        gm.Process(this.gl,((IPEndPoint)this.tcpClient.Client.RemoteEndPoint).Address);
                    }catch (InvalidCastException e){
                        Console.WriteLine (e);
                        Console.WriteLine(o.GetType());
                    }
                }
            } catch (ArgumentNullException e) {
                Console.WriteLine (e);
            } catch (SerializationException e) {
                Console.WriteLine (e);
            }
        }
>  
 On the server side
> 
        public void Send (Game.Message.IGameMessage gm)
        {
            this.xmlSerializerOut.Serialize (stream, gm);
        }
>
The message object
>

namespace Game.Message
{
    [Serializable]
        public class DebugMsgGame: IGameMessage {
          private string debugString;

            public DebugMsgGame(string str){
                this.debugString=str;
            }

            public void Process(Server.IGameListener gl, System.Net.IPAddress ip)
            {
                Console.WriteLine(this.debugString);
                gl.Debug("Someting intelligent");
            }

            new public string ToString(){
              return this.debugString;
            }
        }
}

>

0 个答案:

没有答案