How to send generics over UDP connection C#?

半城伤御伤魂 提交于 2019-12-13 08:36:09

问题


I'm wondering is there a way to send some kind of generics for example List <float> floatValues = new List<float>() need to be sent to udp client. I don't know how to do that, any help will be appreciated!


回答1:


You can serialize floatValues using some serialization facility (like XmlSerializer, BinaryFormatter or DataContractSerializer) and than deserialize it back.

Or you can create your own "application level protocol" and put to the stream type name and serializer type and use this information during deserialization process.




回答2:


What you want to do is known as serialization/deserialization

In computer science, in the context of data storage and transmission, serialization, is the process of converting a data structure or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and "resurrected" later in the same or another computer environment

Instead of building your own serializer, I would recommend to use one of the existing libraries like XmlSerializer, SoapFormatter, BinaryFormatter, DataContractSerializer , DataContractJsonSerializer, JavaScriptSerializer, Json.Net, ServiceStack, Protobuf.Net ........

Here is an example using Json serialization

//Sender
string jsonString = new JavaScriptSerializer().Serialize(floatValues);
byte[] bytesToSend = Encoding.UTF8.GetBytes(jsonString);

//Receiver
string receivedJson = Encoding.UTF8.GetString(bytesToSend);
List<float> floatValues2 = new JavaScriptSerializer()
                                         .Deserialize<List<float>>(receivedJson);


来源:https://stackoverflow.com/questions/13580567/how-to-send-generics-over-udp-connection-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!