Create object instance without invoking constructor?

后端 未结 11 1998
不知归路
不知归路 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: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)

提交回复
热议问题