Question: Singleton Inheritance
I have this class, that implements the singleton pattern, and a subclass.
public class Base{
public static Base Instance;
static Base()
{
System.Type myType = MethodInfo.GetCurrentMethod().DeclaringType;
Instance = (Base)Activator.CreateInstance(myType);
}
public void ID()
{
MessageBox.Show("I am " + this.GetType().Name);
}
}
public class Sub : Base{
}
When I call Base.Instance.ID(), I get "I am Base", which is what I want.
When I call Sub.Instance.ID(), I also get "I am Base". This makes sense,
since MethodInfo.GetCurrentMethod().DeclaringType SHOULD return Base, since that's where it's declared.
The question is - is there any way to tell, when Base's static constructor is called - which object I am, in fact, instantiating? Or, since it's static, there really isn't any Sub object to get info from?
4 Comments
Comments have been disabled for this content.
Jim Arnold said
You could walk back up the stack to get the calling method (the static constructor is 'called' implicitly by the first method accessed on a class). Of course, if the first thing accessed on that class is a field, then the caller will be the method which is accessing that field, which doesn't help you much. I haven't really thought it through, but it might be what you want:
static Base()
{
StackFrame lastFrame = new StackFrame(1);
MethodBase caller = lastFrame.GetMethod();
Console.WriteLine(caller.DeclaringType.Name);
}
Jim
Omer van Kloeten said
Avner,
To get the type use:
Type myType = new System.Diagnostics.StackTrace().GetFrame(2).GetMethod().DeclaringType;
0 is the cctor for the base.
1 is the implicit ctor for the base.
2 is the implicit ctor for the derived.
Jim,
You've missed one of the implicit ctors - the stack frame's constructor should skip 2 frames.
However, it works the same way. :)
Avner Kashtan said
I seem to remember that walking through StackFrames is very slow. True?
Jim Arnold said
Omer,
"1 is the implicit ctor for the base."
Only if you're calling an instance method, surely? It's a bit of a minefield though :-)
"I seem to remember that walking through StackFrames is very slow"
Well, compared to what? And if you're calling it from a static constructor, it's only going to run once anyway.
Jim