将字节数组上的类型错误转换为类对象

时间:2016-07-09 10:26:18

标签: c# serialization deserialization typeconverter

我目前遇到的问题是我无法将我的字节数组转换为类对象。另外,我真的不知道如果我从类对象序列化为字节数组。此外,当我尝试从bytes数组转换为类对象,Visual Studio给了我这个错误:

 An unhandled exception of type 'System.InvalidCastException' occurred in ConsoleApplication15.exe
 Additional information: Unable to cast object of type 'System.Collections.Generic.List`1[ConsoleApplication15.Player]' to type 'ConsoleApplication15.Player[]'.

这是我的代码。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

public static class Program
{
    static void Main(string[] args)
    {
        String name = Console.ReadLine();
        int id = Int32.Parse(Console.ReadLine());

        Player Khanh = new Player(name, id);
        Khanh.testMethod(id);
        List<Player> ipTest = new List<Player>();
        ipTest.Add(Khanh);
        byte [] BytesList = ToByteList(ipTest);
        List<Player> PlayerList = ByteArrayToObject(BytesList).ToList();

        Console.WriteLine(BytesList[1]);
        Console.WriteLine(PlayerList[0]);
        Console.ReadKey();

    }
    public static byte[] ToByteList(List<Player> obj)
    {
        if (obj == null)
            return null;
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
    public static Player [] ByteArrayToObject(byte[] arrBytes)
    {
        MemoryStream memStream = new MemoryStream();
        BinaryFormatter binForm = new BinaryFormatter();

        memStream.Write(arrBytes, 0, arrBytes.Length);
        memStream.Seek(0, SeekOrigin.Begin);

        Player[] obj = (Player[])binForm.Deserialize(memStream);

        return obj;
    }
}
[Serializable]
public class Player
{
   String Name;
    int id;
    public Player(String Name, int id)
    {
        this.id = id;
        this.Name = Name;

    }
    public void testMethod(int n)
    {
        n++;
    }   
    public String getName ()
    {
        return Name;
    }

}

感谢您阅读。

1 个答案:

答案 0 :(得分:1)

您在c411e2方法中使用了错误的返回类型。您返回ByteArrayToObject但当前的返回类型为List<Player>

将此方法更改为:

Player[]