mardi 22 septembre 2015

C# Reflection - find first method in the stacktrace that wasn't part of the consructor for this object

I am trying to use reflection to find the location that an object is being constructed from. I want my code to go in the base class constructor, but it to be able to work out the first method that wasn't part of constructing this object.

class A
{
     public A()
     {
     // reflection goes here
     }
}

class B : A
{
     public B()
     {
     }
}

class C
{
     B b = new B()
}

So here I would like to get back that the B object is being constructed in the constructor of C. (I just need a text representation for some debugging purposes; this is only for debug builds so I don't need to worry about release builds)

So far I have:

var stacktrace = new StackTrace()
var i = 0;
while(stackTrace.GetFrame(i).GetMethod().IsConstructor)
{
    i++
}

This works correctly anywhere that B is being constructed in a standard method - however when (as in the example above) B is being constructed in Cs constructor, it keeps going up the chain.

An option is to check whether method.DeclaringType is an A, which works - except for ideally I could also cope with the case where C inherits from A.

Any other suggestions?





Aucun commentaire:

Enregistrer un commentaire