Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Even though C# doesn't directly support module initialization we can implement it using reflection and static constructors. To do this we can define a custom attribute and use it find classes that need to be initialized on module loading:</p> <pre><code>public class InitOnLoadAttribute : Attribute {} private void InitAssembly(Assembly assembly) { foreach (var type in GetLoadOnInitTypes(assembly)){ var prop = type.GetProperty("loaded", BindingFlags.Static | BindingFlags.NonPublic); //note that this only exists by convention if(prop != null){ prop.GetValue(null, null); //causes the static ctor to be called if it hasn't already } } } static IEnumerable&lt;Type&gt; GetLoadOnInitTypes(Assembly assembly) { foreach (Type type in assembly.GetTypes()) { if (type.GetCustomAttributes(typeof(InitOnLoadAttribute), true).Length &gt; 0){ yield return type; } } } public MyMainClass() { //init newly loaded assemblies AppDomain.CurrentDomain.AssemblyLoad += (s, o) =&gt; InitAssembly(o.LoadedAssembly); //and all the ones we currently have loaded foreach(var assembly in AppDomain.CurrentDomain.GetAssemblies()){ InitAssembly(assembly); } } </code></pre> <p>on classes that we need to initialize immediately we add that code to their static constructor (which will be run once even if the property getter is accessed multiple times) and add the custom attribute we added to expose this functionality.</p> <pre><code>[InitOnLoad] class foo { private static bool loaded { get { return true; } } static foo() { int i = 42; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload