c#serialization ascii confusion

Kel*_*ton 4 .net c# string serialization ascii

这是代码.

[Serializable]
public class HostedGame
{
    public int ID { get; set; }

    public int UID { get; set; }

    public String Name { get; set; }

    public Boolean Available { get; set; }

    public String Description { get; set; }

    public List<int> Users { get; set; }

    public int Port { get; set; }

    public HostedGame(int uid, String name, String description, int port)
    {
        UID = uid;
        Name = name;
        Description = description;
        Available = true;
        Port = port;
        Users = new List<int>();
    }

    public int CompareTo(Object obj)
    {
        int result = 1;
        if(obj != null && obj is HostedGame)
        {
            HostedGame w = obj as HostedGame;
            result = this.ID.CompareTo(w.ID);
        }
        return result;
    }

    static public int Compare(HostedGame x, HostedGame y)
    {
        int result = 1;
        if(x != null && y != null)
        {
            result = x.CompareTo(y);
        }
        return result;
    }

    public static HostedGame DeSerialize(byte[] data)
    {
        MemoryStream ms = new MemoryStream(data);
        BinaryFormatter bff = new BinaryFormatter();
        return (HostedGame)bff.Deserialize(ms);
    }

    public static byte[] Serialize(HostedGame obj)
    {
        BinaryFormatter bff = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bff.Serialize(ms, obj);
        return ms.ToArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

下面的代码似乎不正常:

HostedGame hs = new HostedGame(12,"Name", "Description", 8088);
String s = Encoding.ASCII.GetString(HostedGame.Serialize(hs));
HostedGame HACK = HostedGame.DeSerialize(Encoding.ASCII.GetBytes(s));
Run Code Online (Sandbox Code Playgroud)

HACK.Port 由于某种原因出现7999?

当我这样做的时候......

HostedGame HACK = HostedGame.DeSerialize(HostedGame.Serialize(hs));
Run Code Online (Sandbox Code Playgroud)

它工作正常.

所以,我要问的是

  1. 为什么我的错误值?
  2. 有没有更好的方法将字节转换为字符串然后再返回?

Ale*_*Aza 9

您不能用于Encoding.ASCII.GetString将任何字节数组转换为字符串.执行此操作时,您将丢失一些数据.请Convert.ToBase64String改用.这个将从任何字节序列生成一个字符串而不会丢失数据.

HostedGame hs = new HostedGame(12,"Name", "Description", 8088);
String s = Convert.ToBase64String(HostedGame.Serialize(hs));
HostedGame HACK= HostedGame.DeSerialize(Convert.FromBase64String(s));
Run Code Online (Sandbox Code Playgroud)

这是一个示例,显示了如何使用Encoding.ASCII丢失数据.

var testBytes = new byte[] { 250, 251, 252 };
var text = Encoding.ASCII.GetString(testBytes);
var bytes = Encoding.ASCII.GetBytes(result); // will be 63, 63, 63
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个更好的选择.这是一个工作选择.你不是,所以它隐含更好:) (4认同)