【问题标题】:Get name from variable in calling method - creating calling method signature, parameters and values从调用方法中的变量获取名称 - 创建调用方法签名、参数和值
【发布时间】: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


【解决方案1】:

您可以执行以下“破解”。将方法的签名更改为以下内容:

private static string GenericLog_Exception(
        Exception exceptionData, 
        string extraInformation, 
        params Expression<Func<object>>[] parameters)

现在您的呼叫站点看起来会更干净一点:

GenericLog_Exception(ex, 
                     "it's on fire, please help",
                     () => firstParam,
                     () => secondParam,
                     () => thirdParam);

您可以通过以下方式从表达式中提取参数信息(为方便起见,使用 C# 元组支持):

private static (object Value, string ParamName) GetParameterInfo
    (Expression<Func<object>> expr)
{
    //First try to get a member expression directly.
    //If it fails we know there is a type conversion: parameter is not an object 
    //(or we have an invalid lambda that will make us crash)
    //Get the "to object" conversion unary expression operand and then 
    //get the member expression of that and we're set.
    var m = (expr.Body as MemberExpression) ??
            (expr.Body as UnaryExpression).Operand as MemberExpression;

    return (expr.Compile().Invoke(), m.Member.Name);
}

【讨论】:

  • 就像一个魅力!非常漂亮的解决方案。我要深入这个,从没听说过中间部分。
  • @Obelix 很高兴它有帮助,在中间部分添加了一些解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多