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

标签 c# serialization deserialization tcpclient tcp

我有两个类

[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/

相关文章:

rust - 使用多个模式结构反序列化 XML

c# - 反序列化 JSON - 如何忽略根元素?

c# - 从 C# 中的列表中完全删除所有至少有一个重复项的元素

c# - 确定程序是否为 .NET 中的事件窗口

c# - 使用生物信息学映射 C# 对象方向

c# - 如何使用 DataContract 添加 XML 属性

c# - 为什么内部 .NET 方法比从 .NET 开源复制的简单代码快得多?

c# - 序列化的目的

.net - 如何完全序列化/反序列化 RSAParameters 对象

c# - C#中序列化一个对象并获取字节流