将字节数组上的类型错误转换为类对象
本文关键字:转换 错误 对象 类型 字节 字节数 数组 | 更新日期: 2023-09-27 17:56:18
我目前遇到了无法将字节数组转换为类对象的问题。此外,我真的不知道如果我从类对象序列化为字节数组。此外,当我尝试从字节数组转换为类对象时,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;
}
}
感谢您阅读它。
您在 ByteArrayToObject
方法中使用了错误的返回类型。您返回一个List<Player>
但您当前的返回类型是 Player[]
。
将此方法更改为:
public static List<Player> ByteArrayToObject(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = (List<Player>)binForm.Deserialize(memStream);
return obj;
}