.NET Reflection - Search for a type that defines a static member

I have a problem with reflection. I need to find the type that creates a static member. My code looks like this:

    private class SimpleTemplate : PageTemplate
    {
        internal static readonly IPageProperty NameProperty =
            PropertyRepository.Register("Name");
    }

      

PropertyRepository is a property store (obviously). It keeps track of all properties that have been registered using the type system I am creating.

To do this successfully, I need to keep track of all the properties as well as the type they are defined on. Otherwise, if two properties with the same name are defined, the property repository will not be able to tell them apart.

So, I want to find out the type that the NameProperty defines and store the type as well as the name. How can i do this?

I want to use strong typing i.e. i dont want to send this type as an argument in PropertyRepository.Register. This would be a mistake, since I cannot verify that the type argument is correct.

The solution, I think, would involve reflection. Is there a way to use reflection to determine which type is calling a static method? Static properties are implicitly created using a static constructor (which the compiler generates). Is there a way to get a handle for this constructor? It seems doable, I just can't figure out how to do it.

In other words: if method A calls method B, is there a way that B can tell it was called from A using reflection? I think there is, but I can't figure out how to do it.

Somebody knows?

Edit: I was looking at the StackFrame class, and while it seems to do what I want, it might not be reliable in production code (and I need it).

0


source to share


1 answer


This is almost a duplicate of this question , but not quite. Look at what he answers.

Personally, I think I'll go by type. An alternative could be to use an attribute, for example.



[PropertyName("Name")]
private static readonly IPageProperty NameProperty = null;

static
{
    PropertyRepository.RegisterProperties(typeof(SimpleTemplate));
}

      

PropertyRepostiory.RegisterProperties

can then set the readonly field value using reflection (if that works - I haven't tried it, read-only can be done). It's a bit awkward though ... Alternatively, you can simply fetch the property from the repository when you need it.

+2


source







All Articles