c++/cli static constructor of derived class is not called

限于喜欢 提交于 2019-12-05 22:24:22

I have found a workaround by calling the static constructor manually. I didn't know that this is even possible until I read it a few minutes ago:

System::Runtime::CompilerServices::RuntimeHelpers::RunClassConstructor (
  testAssembly_20::Class20derived::typeid->TypeHandle);

Edit:
Recently I had an issue that my program behaved differently depending on being run from VS2008 (not VS2013 this time!) or from exe, even though I called the static cctor manually.
The problem was that the cctor of the WRONG CLASS was executed! Very weird!
My design:

base A
derived B : A
derived C1 : B
derived C2 : B

I called C2.cctor, but C1.cctor was run. When adding some arbitrary logging commands it behaved different again and eventually worked. That's when I decided to remove the cctors completely and introduce a static Init() instead.

Be prepared to encounter the same!
You can still call the cctor manually, it had worked for me for a long time.

I would have loved to investigate further and analyse the MSIL but I was too busy at that time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!