Reputation: 7264
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();
method.DeclaringType
would return typeof(Base)
. However, I need typeof(A)
. Is it possible to get somehow?
method.ReflectedType
doesn't work either.
Upvotes: 4
Views: 454
Reputation: 15014
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());
}
Upvotes: 0
Reputation: 60190
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.
Upvotes: 4