Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
An explicit static constructor is only guaranteed to run before an instance constructor or static member of the type is called. Therefore, if the type is created without calling an instance constructor, the static constructor is not guaranteed to run.
But suppose there is no user-supplied static constructor. Then what happens?
The C# compiler is not bound by the rules of static constructors in this case, and in fact, does not treat your program as though there was an empty static constructor that has static field initializers in it.
1. Когда вызываются статические конструкторы классов в C#?
Один раз при первом создании экземпляра класса или при первом обращении к статическим членам класса
После каждого обращения к статическим полям, методам и свойствам
Строгий порядок вызова не определен
Статических конструкторов в C# нет
class Singleton
{
public static string S = Echo("Field initializer");
public static string Echo(string s)
{
Console.WriteLine(s);
return s;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting Main...");
if (args.Length == 1)
{
Console.WriteLine(Singleton.S);
}
Console.ReadLine();
}
}
Field initializer
Starting Main...
Несколько вопросов по .NET и C#