Question about MemberInfo.ReflectedType

G

Guest

I'm writing a method (MethodA) that needs to know what method of what class
called it (so it can say, "ClassX called me"). Without having to pass the
type down the chain.
To do this, MethodA walks back up the StackTrace and use GetMethod() looking
for the first method it finds with a custom attribute I created.
The problem I'm having is with derived classes which don't override a method
that calls MethodA. It turns out (in this case) that both DeclaringType and
ReflectedType return the base type rather than the derived type.
I boiled this down to:

namespace Template
{
public class ClassA
{
public virtual string
Declaring
{
get
{
return ( (new System.Diagnostics.StackTrace ( 0 , false
)).GetFrames() [ 0 ].GetMethod().DeclaringType.Name ) ;
}
}

public virtual string
Reflected
{
get
{
return ( (new System.Diagnostics.StackTrace ( 0 , false
)).GetFrames() [ 0 ].GetMethod().ReflectedType.Name ) ;
}
}
}

public class ClassB : ClassA
{
}

public class Template
{
[System.STAThread]
public static void
Main
(
string[] args
)
{
ClassA a = new ClassA() ;
ClassB b = new ClassB() ;

System.Console.WriteLine ( a.Declaring ) ;
System.Console.WriteLine ( a.Reflected ) ;

System.Console.WriteLine ( b.Declaring ) ;
System.Console.WriteLine ( b.Reflected ) ; // Shouldn't this
report ClassB?

return ;
}
}
}

The result is:

ClassA
ClassA
ClassA
ClassA

I can certainly understand why DeclaringType return the base type, but I had
hoped that ReflectedType would return the actual type that called it, and
that the result would be:

ClassA
ClassA
ClassA
ClassB <- note

How can I do this?
Am I doing something wrong?
Is there a better way?
Is ReflectedType broken?
 
J

Jon Shemitz

PIEBALD said:
How can I do this?
Am I doing something wrong?
Is there a better way?
Is ReflectedType broken?

I can't think of a way to do this, right now - but no, it doesn't look
like you're doing anything wrong, and no, I don't think ReflectedType
is broken. It looks like the StackTrace sees a method of ClassA on the
stack, and so uses typeof(ClassA) to get the MethodInfo. (You'd think
that (with instance methods) it could examine the `this` parameter,
but perhaps it can't do this in every case because of optimization,
while the instruction pointer is an unequivocable cue to which method
is running.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top