Create object instance without invoking constructor?

后端 未结 11 1865
不知归路
不知归路 2020-11-28 05:01

In C#, is there a way to instantiate an instance of a class without invoking its constructor?

Assume the class is public and is defined in a 3rd par

相关标签:
11条回答
  • 2020-11-28 05:31

    What you are asking to do is a violation of the philosophy upon which managed programming was developed. The .Net Framework and C# are built with the principle that, whenever possible, objects should be abstracted away from their underlying memory. Objects are objects, not a structured array of bytes. This is why you can't cast objects to void pointers willy-nilly. When objects are abstracted away from their underlying memory, it is fundamentally invalid to suggest that an object instance can exist without the constructor being invoked.

    That said,the .Net framework has made concessions to the fact that in reality, objects are actually represented in memory. With some creativity, it is possible to instantiate value types without invoking their initializers. However, if you feel you need to do it, you're probably doing things wrong.

    0 讨论(0)
  • 2020-11-28 05:36

    See the System.Activator.CreateInstance function.

    0 讨论(0)
  • 2020-11-28 05:40

    I have not tried this, but there is a method called FormatterServices.GetUninitializedObject that is used during deserialization.

    Remarks from MSDN says:

    Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object.

    0 讨论(0)
  • 2020-11-28 05:42

    It might be possible to access the constructor via reflection and invoke it like that (but I'm not sure that it will work since the constructor is internal - you'll have to test it). Otherwise from my knowledge you can't create an object without calling the constructor.

    0 讨论(0)
  • 2020-11-28 05:42

    No one here has quite clarified what is meant by "It can't be done."

    The constructor is what creates the object. Your question is akin to "How can I build a sand castle without shaping it like a castle?" You can't -- All you will have is a pile of sand.

    The closest thing you could possible do is to allocate a block of memory the same size as your object:

    byte[] fakeObject = new byte[sizeof(myStruct)];
    

    (NOTE: even that will only work in MyStruct is a value type)

    0 讨论(0)
提交回复
热议问题