I have an abstract base class, and subclasses who all have an automatically generated Instance static field of their own type, done through using genericity "in between" the base and sub classes (see code below).
When those instances are created, I register them in a dictionary based on specific "identifying" fields overwritten in subclass constructors, in order to access them somewhere else in the code.
I could register them in their constructors, however I don't want to have to drag and copy/paste this same bit of code in every such subclass in order to register them.
public abstract class BaseClass
{
// Declaration of fields and methods
}
public class GenericBaseClass<T> : BaseClass where T : GenericBaseClass<T>
{
private static T instance = ((T) Activator.CreateInstance(typeof(T), true)).Register();
public static T Instance => instance;
public T Register()
{
// Registers Instance in a dictionary.
}
}
public class Subclass1 : GenericBaseClass<Subclass1>
{
private Subclass1()
{
// Modification of protected fields.
}
}
Doing this enables me to call Subclass1.Instance, and by doing so, this instance gets registered in my dictionary, however it doesn't get registered before I try to access it, and only Subclass1 gets that treatment, not other subclasses.
I followed this answer https://stackoverflow.com/a/34726769/13738641 (in the updated section) and made a static constructor for BaseClass and for GenericBaseClass hoping it would initialize static fields for those subclasses, to no avail.
It appears from debugging that the BaseClass static constructor is indeed called, and it does fetch the right subclasses, but it doesn't throw an error, nor does it calls the subclass (static) constructors. Now I could be going crazy, but I could have sworn it worked once before I tried modifying something before reverting back to that, only for it not to work anymore.
I've tried adding a static constructor to the generic class which I hoped would be called once for each subclass, but this constructor only gets called once (when I access some subclass's instance in order to trigger the BaseClass static constructor call).
Any suggestion on what to do to achieve this? I accept suggestion on other ways to achieve something similar (i.e. keep a dictionary generated at runtime with instances of my classes), the subclasses being singletons isn't critical, so maybe I could register constructors instead of instances in the dictionary? I have no idea if that is even possible, with each constructor returning a different type.
Aucun commentaire:
Enregistrer un commentaire