C#中如何获取当前正在执行的代码所在的函数(方法)的名字和参数等信息?

2024-11-30 17:22:11
推荐回答(1个)
回答1:

public static string GetMethodName()
{
var method = new StackFrame(1).GetMethod(); // 这里忽略1层堆栈,也就忽略了当前方法GetMethodName,这样拿到的就正好是外部调用GetMethodName的方法信息
var property = (
from p in method.DeclaringType.GetProperties(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic)
where p.GetGetMethod(true) == method || p.GetSetMethod(true) == method
select p).FirstOrDefault();
return property == null ? method.Name : property.Name;
}
【补充】:其他方法
得到函数名:
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
this.Text = st.GetFrame(0).ToString();
得到代码行,源代码文件名:
StackTrace st = new StackTrace(new StackFrame(true));
Console.WriteLine(" Stack trace for current level: {0}", st.ToString());
StackFrame sf = st.GetFrame(0);
Console.WriteLine(" File: {0}", sf.GetFileName());
Console.WriteLine(" Method: {0}", sf.GetMethod().Name);
Console.WriteLine(" Line Number: {0}", sf.GetFileLineNumber());
Console.WriteLine(" Column Number: {0}", sf.GetFileColumnNumber());