简体   繁体   English

是否可以从堆栈跟踪中获取实际类型?

[英]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.

相关问题 如何从堆栈跟踪中获取行号? - How to get the line number from a Stack Trace? 可以获得堆栈跟踪以查看“导致”某个特定断点的内容? - Possible to get a stack trace to see what 'led up to' a particular breakpoint? 是否可以在堆栈跟踪中获取 NuGet 包的行号? - Is it Possible to Get Line Numbers for NuGet Packages in a Stack Trace? 是否可以使用 .NET 异步方法获得良好的堆栈跟踪? - Is it possible to get a good stack trace with .NET async methods? 从数组获取实际类型 - Get actual type from array 是否可以从堆栈跟踪访问调用者 object 并设置其属性 - Is it possible to access caller object from stack trace and set its property 如何从C#中的堆栈跟踪中识别异常的实际位置或行? - How to identify the actual position or line of the exception from the stack trace in c#? 从Type变量中获取实际类型 - Get the actual type from a Type variable 如果将实际对象类型分配给接口类型,是否可以获取它? - Is it possible to get the actual object type if it is assigned to an interface type? 如何从应用程序见解中获取包含堆栈跟踪的电子邮件例外? - How to get email includes exception with stack trace from application insights?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM