Question:
Is it possible, in some roundabout way (by changing the code within the same Test class), to force the program to call the static constructor of the Test class at the start?
As I understand it, sharp, in some sense, optimizes the program, and does not build static constructors until the class name occurs in the code? Are there any ways to force sharp to build a class that is not mentioned anywhere, but is included in the assembly?
using System;
namespace Program {
public static class Test {
static Test() {
Console.WriteLine("Hello World!");
}
}
public class Activator {
public static void Main(string[] args) {
Console.WriteLine("start...");
}
}
}
Let me explain, I want to see in the console:
hello world!
start…
Answer:
Without an additional call (at least one) that will start the initialization of your types – no, you can't. It is possible with him.
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Program
{
[InvokeStaticCtorAttribute]
public static class Test
{
static Test()
{
Console.WriteLine("Hello World!");
}
}
public class Activator
{
public static void Main(string[] args)
{
InvokeStaticCtorAttribute.InitializeStaticCtors();
Console.WriteLine("start...");
}
}
[AttributeUsage(AttributeTargets.Class)]
public class InvokeStaticCtorAttribute : Attribute
{
public static void InitializeStaticCtors()
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypes())
{
if (type.GetCustomAttribute<InvokeStaticCtorAttribute>() != null)
RuntimeHelpers.RunClassConstructor(type.TypeHandle);
}
}
}
}
}