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

如题所述

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());
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-06-28
在你想要知道的函数开始时新增断点,然后运行程序,就进入了调试,F10是逐步执行,你的IDE下面会有调试窗口,可以看到各个信息
第2个回答  2013-08-23
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;
}本回答被网友采纳
第3个回答  2013-06-28
messageBox。Show()
相似回答