When calling a static method on parent class, can the parent class deduce the type on the child (C#)
- by Matt
Suppose we have 2 classes, Child, and the class from which it inherits, Parent.
class Parent
{
public static void MyFunction(){}
}
class Child : Parent
{
}
Is it possible to determine in the parent class how the method was called? Because we can call it two ways:
Parent.MyFunction();
Child.MyFunction();
My current approach was trying to use:
MethodInfo.GetCurrentMethod().ReflectedType; // and
MethodInfo.GetCurrentMethod().DeclaringType;
But both appear to return the Parent type.
If you are wondering what, exactly I am trying to accomplish (and why I am violating the basic OOP rule that the parent shouldn't have to know anything about the child), the short of it is this (let me know if you want the long version):
I have a Model structure representing some of our data that persists to the database. All of these models inherit from an abstract Parent. This parent implements a couple of events, such as SaveEvent, DeleteEvent, etc. We want to be able to subscribe to events specific to the type. So, even though the event is in the parent, I want to be able to do:
Child.SaveEvent += new EventHandler((sender, args) => {});
I have everything in place, where the event is actually backed by a dictionary of event handlers, hashed by type. The last thing I need to get working is correctly detecting the Child type, when doing Child.SaveEvent.
I know I can implement the event in each child class (even forcing it through use of abstract), but it would be nice to keep it all in the parent, which is the class actually firing the events (since it implements the common save/delete/change functionality).