如何访问反序列化对象的字段

时间:2013-09-17 15:43:06

标签: serialization udp deserialization

我有一个UDP客户端服务器应用程序,它位于c#中,服务器将序列化对象发送到客户端。 在服务器端,对象被反序列化。现在我的问题是如何访问对象的字段或数据成员? 任何建议或帮助将不胜感激。

由于 瓦尼

这是发送对象的服务器代码。

namespace UDP_Client
{
[Serializable]
class SendObject
{
    public int a;
    public int b;
    public int c;
    public SendObject()
    {
        a = 0;
        b = 0;
        c = 0;
    }

}
class ClientSocket
{
    static void Main(string[] args)
    {

        SendObject obj= new SendObject();
        obj.a = 100;
        obj.b = 200;
        obj.c = 300;
        MemoryStream memorystream = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(memorystream,obj);
        Send(obj.ToString());


    }
    static void Send(string Message)
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPAddress broadcast = IPAddress.Parse("127.0.0.1");
        byte[] sendbuffer = Encoding.ASCII.GetBytes(Message);
        IPEndPoint ep = new IPEndPoint(broadcast, 10000);
        s.SendTo(sendbuffer, ep);
        s.Close();

    }
}

}

这是接收来自服务器的对象的客户端。             UdpClient listener = new UdpClient(listenPort);             IPEndPoint groupEP = new IPEndPoint(IPAddress.Any,listenPort);

                byte[] bytes = listener.Receive(ref groupEP);

                MemoryStream stream = new MemoryStream();
                BinaryFormatter formatter = new BinaryFormatter();
                stream.Seek(0, SeekOrigin.Begin);
                Object obj = (Object)formatter.Deserialize(stream);
                int val1 = obj.a;//This is what i want to do.

0 个答案:

没有答案