[英]Is it possible to get the actual type from a stack trace?
I'm writing an ExceptionFactory class, using System.Diagnostics.StackTrace
. 我正在编写一个ExceptionFactory类,使用
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();
method.DeclaringType
would return typeof(Base)
. method.DeclaringType
将返回typeof(Base)
。 However, I need typeof(A)
. 但是,我需要
typeof(A)
。 Is it possible to get somehow? 有可能得到某种方式吗?
method.ReflectedType
doesn't work either. method.ReflectedType
也不起作用。
No, since the method is actually declared on Base
. 不,因为该方法实际上是在
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. 只要不覆盖该方法,就始终为该方法获取相同的
MethodInfo
实例,而不管您是在基类还是在派生类上查询它。
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()
. 是的,只需使用
this.GetType()
。 That will return the subclass. 这将返回子类。 So the following code snippet should print "A".
因此,以下代码段应打印“A”。
public void Foo()
{
System.Diagnostics.Debug.Print(this.GetType().ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.