There is a class
public class A { public A() { } static A() { Console.WriteLine("Call Static Constructor A"); } public static A CreateA(Type typeA) { System.Reflection.ConstructorInfo constructorInfo = typeA.GetConstructor(new Type[0]); Console.WriteLine("Call CreateA Constructor"); A a = (A)constructorInfo.Invoke(new object[0]); return a; } } public class B : A { static B() { Console.WriteLine("Call Static Constructor B"); } public B() : base() { Console.WriteLine("Call Constructor B"); } }
There is a code
A a = A.CreateA(typeof(B));
Console output
Call Static Constructor A
Call CreateA Constructor
Call Static Constructor B
Call constructor b
Why Call CreateA Constructor
is called before Call Static Constructor B
and how to make it so that any type B
, even typeof(B)
or typeof(B).GetConstructor
called static B()
, but it turns out that public B() : base()
is executed before static B()
UPD: And is it possible to take all types of classes inherited from the current class?
UPD: A crutch that calls the first static property of all heirs of class
A
to force a static constructor of each of them ... static static A() { Type[] allAssignableTypes = (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies() from assemblyType in domainAssembly.GetTypes() where typeof(A).IsAssignableFrom(assemblyType) select assemblyType).ToArray(); foreach (Type type in allAssignableTypes) { PropertyInfo p = type.GetProperties().FirstOrDefault(x => x.GetMethod.IsStatic); if (p != null) p.GetValue(null); } }
A
were executed ... - Dmitry ChistikA
in the static constructor, all static heirs are called if they have static properties. In principle, what I needed was - Dmitry Chistik