问题
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