Reputation: 113
I'm trying to makes something, where all classes derived from some base class have some operation performed when they are loaded, but only once during the execution of the program. I'd like to make it so the person making the derived class doesn't have to do any extra work. In my example, I have OnInheritedAttribute(), which I have just made up, which would call the entered delegate when a child class is defined.
public class DelegateHolder
{
public bool Operation(Type t) { /*...*/ };
static OnInheritedAttributeDelegate d = new OnInheritedAttributeDelegate(Operation);
}
[OnInheritedAttribute(DelegateHolder.d)]
public abstract class AInheritable
{ /*...*/ }
//ideally, I could do this, and have the processing done
public class SubClassA : AInheritable
{ /*...*/ }
//which would have the same effect as this, no attribute were assigned to AInheritable
public class SubClassB : AInheritable
{
private static readonly bool _dummy = DelegateHolder.Operation(SubClassB);
}
I'm almost positive the second method will do what I want (provided the assembly isn't loaded multiple times), but it seems like it would be really annoying to have every subclass of AInheritable required to call this code.
Another option might be
public class BaseClass
{
static bool initialized; //this may not work, it will probably make one value for all classes rather than each subclass.
public BaseClass()
{
if(!/*System.Reflection code to get static member initialized from class of (this)*/)
{
/*perform registration*/
/*System.Reflection code to get static member initialized from class of (this)*/ = true;
}
}
}
But this seems clunky, and wasteful if a lot of objects are going to be created.
Any advice on streamlining this?
Upvotes: 2
Views: 105
Reputation: 19203
It sounds like you want a static initializer that is inherited, since static properties are not inherited, this does not work directly.
However you do have the option to add logic to the base class constructor. Adding some logic to handle multiple types, and using this.GetType() to get the current type. For instance:
private static HashSet<Type> initializedTypes = new HashSet<Type>();
public BaseClass()
{
if (!initializedTypes.Contains(this.GetType())
{
//Do something here
initializedTypes.Add(this.GetType());
}
}
Upvotes: 3