Reputation: 554
I've recently started learning Reflection.Emit, so I could replace all the Activator usages for better performance in my code. I'm currently thinking about some kind of serialization and deserialization library. Especially for deserialization I'd like to recreate the state of object exactly the same, as it was before serialization (I assume serialization is 100% correct). However, e.g. there can be class, that have multiple constructors, and every one does something sophisticated, because this object has complicated logic and has to be initialized some specific way. But when I have serialized everything about the object, the simplest thing I could do is somehow bypass any of the provided ctors - just make an empty object and fill it's all fields with data. Period.
Unfortunately, usage of OpCodes.Newobj
in ILGenerator.Emit
requires passing ConstructorInfo
as parameter. For structs it would be easy, as they always have default parameterless ctor. However with classes things are different.
I would appreciate any help.
Upvotes: 1
Views: 184
Reputation: 171246
It must be possible because BinaryFormatter creates objects without calling constructors.
You can use FormatterServices.GetSafeUninitializedObject
. This is probably protected by highest security requirements.
Upvotes: 3