我有一些历史代码,我们希望获得有关如何使用某些方法的一些数据。我正在尝试使用反射访问调用方法的名称以及执行方法的名称。但是我似乎只能得到外部调用方法的名称。
我们有一个执行类似这样的源方法:
public class DataBinder
{
public IEnumerable<object> FindData(string id)
{
var data = Helper.MeasureExecution(() => DataHelper.GetData(id), MethodBase.GetCurrentMethod());
return data;
}
}
以及静态Helper
类中的方法,其执行以下操作:
public static T MeasureExecution<T>(Func<T> func, MethodBase sourceMethod)
{
T funcResult;
funcResult = func();
try
{
var executingMethod = string.Empty;
if (func.Method!= null)
{
executingMethod = func.Method.Name;
}
LogDetails($"Method Being Executed: {executingMethod}, Executing Source Class: {sourceMethod.ReflectedType.Name}, Executing Source Method: {sourceMethod.Name});
}
catch { }
return funcResult;
}
我想得到以下"Method Being Executed: GetData, Executing Source Class: DataBinder, Executing Source Method: FindData"
,但我总是得到"Method Being Executed: FindData, Executing Source Class: DataBinder, Executing Source Method: FindData"
。
这与lambda表达式是静态的有关,还是我在这里缺少基本的东西?
public static T MeasureExecution<T>(Expression<Func<T>> func, MethodBase sourceMethod)
{
T funcResult;
funcResult = func.Compile()();
try
{
var executingMethod = string.Empty;
var methodExpression = func.Body as MethodCallExpression;
if (methodExpression != null)
{
executingMethod = methodExpression.Method != null ? methodExpression.Method.Name : "Cannot find method details";
}
MethodInformation = string.Format("Method Being Executed: {0}, Executing Source Class: {1}, Executing Source Method: {2}", executingMethod, sourceMethod.ReflectedType.Name, sourceMethod.Name);
}
catch { }
return funcResult;
}
public static string MethodInformation { get; private set; }
这是我得到的输出-
正在执行的方法:GetData,正在执行的源类:DataBinder,正在执行的源方法:FindData