I have a problem with reflection. I need to find the type that instantiates a static member. My code looks like this:
private class SimpleTemplate : PageTemplate
{
internal static readonly IPageProperty NameProperty =
PropertyRepository.Register("Name");
}
The PropertyRepository is a repository of properties (obviously). It keeps track of all the properties that have been registered using the type system that I'm building.
In order to do that successfully, I need to keep track of all the properties but also the type on which they are defined. Otherwise, if two properties with the same name are defined, the property repository won't be able to tell them apart.
So, what I want to do is to find out the type that defines the NameProperty and store the type as well as the name. How can I do that?
I want to use strong typing, i.e. I do not want to send the type as an argument to PropertyRepository.Register. That would be error-prone since I can't validate that the type argument is correct.
The solution, I imagine, would involve reflection. Is there any way to use reflection to determine which type calls a static method? The static properties are implicitly instantiated using a static constructor (that the compiler generates). Is there a way for me to get a handle to that constructor? That seems feasible, I just cannot figure out how to do that.
In other words: If method A calls method B, is there any way B can tell that it was called from A using reflection? I imagine there is, but I cannot find out how.
Does anyone know?
Edit: I've looked at the StackFrame class and while it seems to do what I want, it may not be reliable in production code (and I need that).