简体   繁体   中英

c# How to recieve and parse object with arrays of primitive fields from socket

I'm new with .net(C#).

I need to write an application which gets objects from socket and display it on screen.

The other application which send the messages is not c# (it's c++ if it's matter)

The ICD of the objects is:

int id;
char name[20];
short rates[5]
int lastGrades[10];
  1. How can I define this object in c# ? (It seems that I cant define class with primitve array without using new operator)

I want to do somthing like that to get the message from socket and cast it to my MyObject class.

somthing like:

byte b[] = new byte[100];
socket.Recvive(b);
MyObject myObject = ???cast??? b;
  1. How can I do it ?

Here is an example for you

public class ICD {

   public int Id { get; set; }
   public string Name { get; set; }
   public short[5] Rates { get; set; }
   public int[5] Grades { get; set; }


   public byte[] Serialize() {
      using (MemoryStream m = new MemoryStream()) {
         using (BinaryWriter writer = new BinaryWriter(m)) {
            writer.Write(Id);
            writer.Write(Name);
         }
         return m.ToArray();
      }
   }

   public static ICD Desserialize(byte[] data) {
      ICD result = new ICD();
      using (MemoryStream m = new MemoryStream(data)) {
         using (BinaryReader reader = new BinaryReader(m)) {
            result.Id = reader.ReadInt32();
            result.Name = reader.ReadString();
         }
      }
      return result;
   }

}

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