簡體   English   中英

c#如何從socket接收和解析具有原始字段數組的對象

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

我是.net(C#)的新手。

我需要編寫一個從套接字獲取對象並在屏幕上顯示它的應用程序。

發送消息的另一個應用程序不是c#(如果有問題就是c ++)

對象的ICD是:

int id;
char name[20];
short rates[5]
int lastGrades[10];
  1. 如何在c#中定義此對象? (似乎我不能使用primitve數組定義類而不使用new運算符)

我想做類似的事情來從socket獲取消息並將其轉換為我的MyObject類。

像這樣的東西:

byte b[] = new byte[100];
socket.Recvive(b);
MyObject myObject = ???cast??? b;
  1. 我該怎么做 ?

這是一個例子

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;
   }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM