开发者

Stop static constructor

开发者 https://www.devze.com 2023-01-18 06:28 出处:网络
How to stop a static constructor(i.e开发者_StackOverflow社区. module constructor & type constructor) from running in .NET?

How to stop a static constructor(i.e开发者_StackOverflow社区. module constructor & type constructor) from running in .NET?

For example:

class A  
{  
    static A()  
    {  
        Environment.Exit(0);  
    }  
    static int i()  
    {  
        return 100;
    }  
}  

How to invoke i() without exiting?


How to stop a static constructor from running in .NET?

You can't do this. Static constructor will be invoked before any instance of the type is created or any static member is referenced. It's called by the CLR and you have absolutely no control over the exact timing.

So the only way to avoid calling the static constructor is to never reference and using the type that contains this static constructor. Why would you define a static constructor in the first place if you don't want it to be executed? Putting an Environment.Exit(0) instruction into a static constructor is like taking a gun and shooting yourself into the leg.


Actually i am making a interpreter of .net,

If you use

  System.Reflection.Assembly.ReflectionOnlyLoadFrom(fileName);

The static ctor won't run.


As others have mentioned, if you load the type, the static constructor will run. There's no way around it.

You can use Cecil or MS CCI. Both of them allow you to inspect a type without loading it. You can create a dynamic type by cloning class A, and remove the static constructor and finally create the modified type.

0

精彩评论

暂无评论...
验证码 换一张
取 消