使用 ISerializationSurrogate 时对象是如何创建的?

How is the object created when using ISerializationSurrogate?

我使用 ISerializationSurrogate。在 object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) 中,obj 将是空的新对象。

MSDN 说:

在反序列化过程中调用了 SetObjectData 方法。使用此方法,您可以将已经创建的空Object obj,并输入SerializationInfo info data 到该对象中。在信息反序列化和对象重建期间不调用构造函数。

我的问题是:如何创建对象?也许有人可以向我指出发生这种情况的 http://www.sourceof.net 处的代码?

对象由 FormatterServices.GetUninitializedObject method. The code where this is called from is here 创建。

GetUninitializedObject 的实现在 CLR 本身很深,如果您真的有兴趣,可以查看源代码here

如果您有 de/serialize 的对象源,最好实现 ISerializable 并使用特殊构造函数,因为您可以从那里设置只读字段。使用代理时,您只能通过反射设置只读字段,这不仅速度慢而且需要完全信任权限。