【发布时间】:2017-12-07 17:09:53
【问题描述】:
我正在寻找一种方法来获取传递给扩展方法的变量的名称。我想在调用变量中有参数的名称。听起来很奇怪,让我解释一下。
假设这段测试代码
private static void TestingMethod(string firstParam, int secondParam, bool thirdParam)
{
try
{
throw new InvalidOperationException("This named optional params stuff, it's just not working boss");
}
catch (Exception ex)
{
GenericLog_Exception(ex, "it's on fire, please help");
}
}
在最后一行,您可以看到正在记录的异常。我希望能够提供可选参数支持。所以开发者可以在需要的时候添加参数信息。
我在 stackoverflow 上看过很多关于此的帖子,有很多不同的方法。主要的是;它不能完全通用。
一些解释代码:
static string GetCallingMethodSignature()
{
StackTrace stackTrace = new StackTrace();
// Get calling method name
var callingMethod = stackTrace.GetFrame(1).GetMethod();
var callingMethod_Name = callingMethod.Name;
// get calling method params
string retVal = string.Empty;
var callingMethod_Parameters = callingMethod.GetParameters();
retVal = callingMethod_Name + "(";
foreach (var param in callingMethod_Parameters)
{
retVal += param.Name + ": " + param.ToString() + ",";
}
retVal.Remove(retVal.Length - 1, 1);
retVal += ")";
return retVal;
}
现在,此测试代码正在获取调用方法名称及其参数。即参数的名称。但不是他们的价值观。 param.tostring() 部分仅返回类型名称。不是价值。我一直在阅读这方面的内容,看来这无法通过反射来完成。
所以我选择了另一种方法,为什么不提供开发人员认为适合记录的参数。无论如何,大多数时候你并不需要所有这些。
private static string GenericLog_Exception(Exception exceptionData, string extraInformation, params KeyValuePair<string, object>[] parameters)
所以,这是一个新的测试方法,我将选择的参数提供给异常记录方法。但是,如果您想完成这项工作,那么每次拨打这个电话都是一项艰巨的工作。
private static void TestingMethod(string firstParam, int secondParam, bool thirdParam)
{
try
{
throw new InvalidOperationException("This named optional params stuff, it's just not working boss");
}
catch (Exception ex)
{
GenericLog_Exception(ex, "it's on fire, please help", new KeyValuePair<string, object>[]{
new KeyValuePair<string, object>("firstParam", firstParam),
new KeyValuePair<string, object>("secondParam", secondParam),
new KeyValuePair<string, object>("thirdParam", thirdParam)
});
}
}
现在这正在工作。但正如所说,我发现底部很麻烦。我在考虑扩展方法的思路,所以我可以缩短每个 kvp 的创建时间。
internal static class ExtensionMethodsForTesting
{
internal static KeyValuePair<string, object> AsKeyValuePair(this string parameter)
{
var name = nameof(parameter);
return new KeyValuePair<string, object>(name, parameter);
}
}
然后这将被用作
GenericLog_Exception(ex, "it's on fire, please help", new KeyValuePair<string, object>[] { firstParam.AsKeyValuePair() });
这让我遇到了同样的问题;当然,nameof(parameter) 返回“参数”。我还必须为每种类型制作几个扩展方法。或者检查扩展方法中的类型以确保我得到正确的值。
那么,简而言之:我怎样才能获得调用扩展方法的这个变量的名称?
【问题讨论】:
-
你试过
[CallerMemberName] string propertyName = null吗? -
@Nekeniehl :我正在获取调用方法的名称,在本例中为“TestingMethod”。
标签: c# logging reflection extension-methods stack-trace