且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎样才能获得在C#中调用方法

更新时间:2022-10-15 17:07:35

从 href=\"http://www.csharp-examples.net/reflection-calling-method-name/\">http://www.csharp-examples.net/reflection-calling-method-name/
 使用System.Diagnostics程序;//获取调用堆栈
堆栈跟踪堆栈跟踪=新的堆栈跟踪();//获取调用方法名
Console.WriteLine(stackTrace.GetFrame(1).GetMethod()名称。);

Possible Duplicate:
How can I find the method that called the current method?

I need a way to know the name of calling methods in C#.

For instance:

private void doSomething()
{
// I need to know who is calling me? (method1 or method2).

// do something pursuant to who is calling you?
} 

private void method1()
{
 doSomething();
}

private void method2()
{
 doSomething();
}

from http://www.csharp-examples.net/reflection-calling-method-name/

using System.Diagnostics;

// get call stack
StackTrace stackTrace = new StackTrace();

// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);