Executing code before .NET's Main() method

假装没事ソ 提交于 2021-02-07 13:31:10

问题


Is it possible to execute any user-provided code before the .NET Main method?

It would be acceptable if the code had to be unmanaged.

The reason for asking is that this might be a way to solve the problem of calling SetCurrentProcessExplicitAppUserModelID before any UI elements are displayed (as mentioned in Grouping separate processes in the Windows Taskbar)


回答1:


In C# you can add a static constructor to the class which contains the main method. The code in the static constructor will be executed before main.




回答2:


A static constructor will execute before Main, but only if the class is actually being referenced by something. Eg:

class ClassWStaticCon
{
    static ClassWStaticCon()
    {
        Console.WriteLine("Hello world!");
    }
}

...
static void Main(string[] args)
{
    Console.WriteLine("Hello main.");
}

Will print:

Hello main.

class ClassWStaticCon
{
    public static int SomeField;
    static ClassWStaticCon()
    {
        Console.WriteLine("Hello world!");
    }
}

...
static void Main(string[] args)
{
    ClassWStaticCon.SomeField = 0;
    Console.WriteLine("Hello main.");
}

Will print:

Hello world! Hello main.

If you want to control the order of execution then use a Queue of Action delegates http://msdn.microsoft.com/en-us/library/018hxwa8.aspx in a single static 'initialize all pre main stuff' class.



来源:https://stackoverflow.com/questions/13946024/executing-code-before-nets-main-method

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