2

I have a Type object, and a method name:

Type type;  
string methodName;  

And i need a MethodBase object for the method "methodName", somewhere in the stack.
This works:

MethodBase nemo;
StackTrace st = new StackTrace(); // Behaves poorly...
for(int i =0; i< st.FrameCount; i++ )
{
   StackFrame sf = st.GetFrame(i);
   if (sf.GetMethod().Name == methodName)
   {
       nemo = sf.GetMethod();      
   }
}

But i need a faster approach...

seldary
  • 6,186
  • 4
  • 40
  • 55

1 Answers1

0

You can write type.GetMethod(methodName).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • He apparently wants an instance of that method as it appears in the call stack, not a new one that isn't currently executing. – KeithS May 16 '11 at 18:20
  • @Keith: Methods don't have instances. That doesn't make any sense. – SLaks May 16 '11 at 18:22
  • @KeithS - Reflection metadata doesn't look any different whether you get it from the callstack, or from the type. Walking the callstack is only necessary if you don't know *which siganture of the method may appear* - in which case, it's unavoidable. – LBushkin May 16 '11 at 18:22
  • @SLaks: Thanks, but it is not the same - it does not work for constructors... type.GetMethod(".ctor") returns null. StackFrame.GetMethod worked for every method. – seldary May 17 '11 at 07:34
  • @seldary: Then call `.GetConstructors()`. – SLaks May 17 '11 at 12:32
  • @SLaks: I too can read msdn... and even if use it i don't know which ctor was called. and there are other problems aside from ctors. i need a WORKING solution (exactly as the StackFrame solution), and a FAST one at the same time. – seldary May 18 '11 at 04:22