gpt4 book ai didi

c# - 如何知道反序列化类的类型??(或对象)

转载 作者:可可西里 更新时间:2023-11-01 02:39:12 27 4
gpt4 key购买 nike

我有两个类(class)

[Serializable]    
public class Class1
{
public List<String[]> items= new List<string[]>();
}

[Serializable]
public class Class2
{
public List<String[]> items = new List<string[]>();
}

然后我序列化这些类并像这样将数据发送给客户端

NetworkStream stream = client.GetStream();
MemoryStream memory = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();

Class1 data = new Class1(); // or Class2
data.items.Add(new String[]{"1", "2", "3"});

bf.Serialize(memory, data);
memory.Position = 0;

byte[] buffer = memory.ToArray();

stream.Write(buffer, 0, buffer.Length);
stream.Flush();

当客户端程序从服务器端接收到数据时,程序会这样处理数据

BinaryFormatter bf = new BinaryFormatter();
MemoryStream memory = new MemoryStream();
NetworkStream stream = client.GetStream();

int bufferSize = client.ReceiveBufferSize;
byte[] buffer = new byte[bufferSize];
int bytes = stream.Read(buffer, 0, buffer.Length);

memory.Write(buffer, 0, buffer.Length);
memory.Position = 0;

但是在这种情况下,我不知道数据的类型是什么...是 Class1???或 Class2..

如何知道反序列化类的类型??(或对象)

最佳答案

您应该能够将其反序列化为一个对象,然后使用 GetType()

GetType(new BinaryFormatter().Deserialize(stream));

关于c# - 如何知道反序列化类的类型??(或对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31402157/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com