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

C# 如何知道反序列化类(或对象)的类型,c#,serialization,deserialization,tcpclient,tcp-ip,C#,Serialization,Deserialization,Tcpclient,Tcp Ip,我有两节课 [Serializable] public class Class1 { public List<String[]> items= new List<string[]>(); } [Serializable] public class Class2 { public List<String[]> items = new List<string[]>();

我有两节课

[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是什么???或者第二类


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

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


GetType(新的BinaryFormatter().反序列化(流))

最好确保
流中序列化对象的类型。
也就是说,您应该定义一些顺序或协议,以保证流中的第一个对象是
Class1
的实例,然后是
Class2
的实例

这样做,您可以或多或少地控制它:从流中获得
Class1
的反序列化实例,您可以根据
Class1
对象中的数据决定流中下一个对象

另一种解决方案是将
Class1
Class2
的对象包装到某个容器类中,然后只序列化该容器的对象。 如果每次都需要序列化相同类型的对象,就可以了

但是,如果您只需要检查类型,那么在反序列化了流中的任何对象之后,您可以通过比较其类型标记或安全强制转换,通过
is
-check来检查其类型。请参见示例:

object d = binaryFormatter.Deserialize(stream);
Class1 c1 = null;
if ((c1 = d as Class1) != null) {
    //do something with c1
}

我提供将一个字节添加到从对象反序列化的字节头数组中,在服务器中,您只需检查第一个字节即可知道该缓冲区的类别。这将提高服务器性能

switch(buffer[0])
{
    case DataType.NORMAL:
    ...
    break;
    case DataType.FILE_TRANSFER:
    ...
    break;
    ....
}

或者他可以检查反序列化对象是Class1还是Class2类型。@LasseV.Karlsen,谢谢,我明白了,我会更新答案。但是,是的,我完全同意你的看法,他应该尝试避免包含“未知数量和类型的对象”的序列化流。但是GetType()只显示MemoryStream。我只想知道MemoryStream的类型,因为您尚未将其反序列化为对象。使用新的BinaryFormatter()
并调用
反序列化()
并将内存流传递给它。然后对对象执行
GetType()
。我建议使用2个字节。基于这个问题,我认为只需要一个字节,如果他想要更多的信息,他可以添加更多的字节