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

I am 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(); 

method.DeclaringType will return typeof(Base) . However, I need typeof(A) . Is there any way to get there?

method.ReflectedType does not work either.

+4
source share
2 answers

No, because the method is actually declared on Base . Until the method is overridden, you always get the same MethodInfo instance for the method, regardless of whether you request it in a base class or a derived class.

But why do you need a different type in the first place? Perhaps there is another solution to your problem, so I ask about it.

+4
source

Yes, just use this.GetType() . This will return the subclass. Therefore, the following code fragment should print "A".

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

Source: https://habr.com/ru/post/1337768/


All Articles