当登录c#时,我如何才能知道调用当前方法的方法的名称?我知道所有关于System.Reflection.MethodBase.GetCurrentMethod(),但我想在堆栈跟踪中走一步。我考虑过解析堆栈跟踪,但我希望找到一种更清晰、更显式的方式,比如Assembly.GetCallingAssembly(),但用于方法。
当前回答
额外信息给Firas Assaad回答。
我已经使用了新的StackFrame(1).GetMethod().Name;在.net核心2.1依赖注入和我得到调用方法为“开始”。
我尝试使用[System.Runtime.CompilerServices。CallerMemberName = "" 并给出了正确的调用方法
其他回答
我们可以对阿萨德先生的代码(目前公认的答案)稍加改进,只实例化我们实际需要的帧而不是整个堆栈:
new StackFrame(1).GetMethod().Name;
这可能会执行得更好一些,尽管在所有的可能性中,它仍然需要使用整个堆栈来创建单个帧。此外,它仍然有Alex Lyman指出的同样的警告(优化器/本机代码可能会破坏结果)。最后,你可能想要检查以确保新的StackFrame(1)或. getframe(1)不返回null,因为这种可能性看起来不太可能。
请看这个相关问题: 您可以使用反射来查找当前正在执行的方法的名称吗?
要获得方法名和类名,请尝试以下方法:
public static void Call()
{
StackTrace stackTrace = new StackTrace();
var methodName = stackTrace.GetFrame(1).GetMethod();
var className = methodName.DeclaringType.Name.ToString();
Console.WriteLine(methodName.Name + "*****" + className );
}
/// <summary>
/// Returns the call that occurred just before the "GetCallingMethod".
/// </summary>
public static string GetCallingMethod()
{
return GetCallingMethod("GetCallingMethod");
}
/// <summary>
/// Returns the call that occurred just before the the method specified.
/// </summary>
/// <param name="MethodAfter">The named method to see what happened just before it was called. (case sensitive)</param>
/// <returns>The method name.</returns>
public static string GetCallingMethod(string MethodAfter)
{
string str = "";
try
{
StackTrace st = new StackTrace();
StackFrame[] frames = st.GetFrames();
for (int i = 0; i < st.FrameCount - 1; i++)
{
if (frames[i].GetMethod().Name.Equals(MethodAfter))
{
if (!frames[i + 1].GetMethod().Name.Equals(MethodAfter)) // ignores overloaded methods.
{
str = frames[i + 1].GetMethod().ReflectedType.FullName + "." + frames[i + 1].GetMethod().Name;
break;
}
}
}
}
catch (Exception) { ; }
return str;
}
从。net 4.5开始,你可以使用调用者信息属性:
CallerFilePath - The source file that called the function; CallerLineNumber - Line of code that called the function; CallerMemberName - Member that called the function. public void WriteLine( [CallerFilePath] string callerFilePath = "", [CallerLineNumber] long callerLineNumber = 0, [CallerMemberName] string callerMember= "") { Debug.WriteLine( "Caller File Path: {0}, Caller Line Number: {1}, Caller Member: {2}", callerFilePath, callerLineNumber, callerMember); }
这一设施也出现在“。NET Core"和"。净标准”。
参考文献
微软-呼叫者信息(c#) CallerFilePathAttribute类 CallerLineNumberAttribute类 CallerMemberNameAttribute类
我们也可以用来找到调用者。
假设你有一个你定义的方法:
public void MethodA()
{
/*
* Method code here
*/
}
你想找到它的调用者。
1. 改变方法签名,这样我们就有了一个Action类型的参数(Func也可以):
public void MethodA(Action helperAction)
{
/*
* Method code here
*/
}
2. Lambda名称不是随机生成的。规则似乎是:> <CallerMethodName>__X 其中CallerMethodName被前面的函数替换,X是一个索引。
private MethodInfo GetCallingMethodInfo(string funcName)
{
return GetType().GetMethod(
funcName.Substring(1,
funcName.IndexOf(">", 1, StringComparison.Ordinal) - 1)
);
}
3.当我们调用MethodA时,Action/Func参数必须由调用方方法生成。 例子:
MethodA(() => {});
4. 在MethodA内部,我们现在可以调用上面定义的helper函数,并找到调用方方法的MethodInfo。
例子:
MethodInfo callingMethodInfo = GetCallingMethodInfo(serverCall.Method.Name);
推荐文章
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- Python日志记录不输出任何东西
- 转换为值类型'Int32'失败,因为物化值为空