📜  c# 类到字节数组 - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:18             🧑  作者: Mango

代码示例3
private byte[] ObjectToByteArray(object obj)
{
  // proper way to serialize object
  var objToString = System.Text.Json.JsonSerializer.Serialize(obj);
  // convert that that to string with ascii you can chose what ever encoding want
  return System.Text.Encoding.ASCII.GetBytes(objToString);
}

private object ByteArrayToObject(byte[] bytes)
{
  // make sure you use same type what you use chose during conversation
  var stringObj = System.Text.Encoding.ASCII.GetString(bytes);
  // proper way to Deserialize object
  return System.Text.Json.JsonSerializer.Deserialize(stringObj));
}