开发者

Is it possible to get the actual type from a stack trace?

开发者 https://www.devze.com 2023-02-08 04:06 出处:网络
I\'m writing an ExceptionFactory class, using System.Diagnostics.StackTrace. var trace = new StackTrace(1, true);

I'm writing an ExceptionFactory class, using System.Diagnostics.StackTrace.

 var trace = new StackTrace(1, true);
 var frames = trace.GetFrames();
 var method =  frames[0].GetMethod();

Now, for classes

class Base
{
   public void Foo()
   {
      //Call ExceptionFactory from here
   }
} 
class A : Base {}

//...

var x = new A();
x.Foo();

m开发者_如何学运维ethod.DeclaringType would return typeof(Base). However, I need typeof(A). Is it possible to get somehow?

method.ReflectedType doesn't work either.


No, since the method is actually declared on Base. As long as the method is not overridden, you always get the same MethodInfo instance for the method independent of whether you query it on the base class or on the derived class.

But why do you need the other type in the first place? There may be another solution to your problem, that's why I'm asking this.


Yeah, just use this.GetType(). That will return the subclass. So the following code snippet should print "A".

public void Foo()
{
    System.Diagnostics.Debug.Print(this.GetType().ToString());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消