1、返回当前方法所在的类名:
using System.Reflection;
sting className = MethodBase.GetCurrentMethod().ReflectedType.Name;
2、返回调用当前方法的方法名:
using System.Diagnostics;
using System.Reflection;
StackTrace trace = new StackTrace();
StackFrame frame = trace.GetFrame(1);
MethodBase method = frame.GetMethod();
String className = method.ReflectedType.Name;
String methodName = method.Name;
3、返回最外面调用当前方法的方法名:
trace.GetFrame(1).GetMethod();
这个括号里面的参数从0开始,0就是自己,1就是上一个,2就是上上一个3就是上上上一个
如果再上面没有了的话,就会返回一个异常字符串,你判断这个异常字符串是什么,就停止循环就好了
eg:打印日志的时候记录类名和方法名
public static void WriteLog(string log)
{
StackTrace trace = new StackTrace();
StackFrame frame = trace.GetFrame(1);
MethodBase method = frame.GetMethod();
String className = method.ReflectedType.Name;
String methodName = method.Name;
string filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
filepath = filepath + "\\" + DateTime.Now.ToString("yyyyMMdd");
string filename = Path.Combine(filepath, DateTime.Now.ToString("yyyyMMdd") + ".log");
StreamWriter mvarStreamLog = null;
try
{
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
mvarStreamLog = new StreamWriter(filename, true);
mvarStreamLog.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss:ffff") + " : " + log + " (ClassName:" + className + " MethodName:" + methodName + ")");
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
finally
{
if (mvarStreamLog != null)
mvarStreamLog.Close();
}
}