如何在 C# 中获取调用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/394850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How I can get the calling methods in C#
提问by ecleel
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#.
我需要一种方法来知道 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();
}
采纳答案by Andrew Robertson
from http://www.csharp-examples.net/reflection-calling-method-name/
来自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);
回答by John Saunders
You almost certainly don't want to do this. A caller should never know who is calling it. Instead, the difference between the two callers should be abstracted into a parameter, and passed into the method being called:
你几乎肯定不想这样做。调用者永远不应该知道是谁在调用它。相反,两个调用者之间的差异应该抽象为一个参数,并传递到被调用的方法中:
private void doSomething(bool doItThisWay)
{
if (doItThisWay)
{
// Do it one way
}
else
{
// Do it the other way
}
}
private void method1()
{
doSomething(true);
}
private void method2()
{
doSomething(false);
}
This way, if you add a method3, it can either doSomething one way or the other, and doSomething won't care.
这样,如果您添加方法 3,它可以以一种方式或另一种方式 doSomething,doSomething 不会在意。