Finding the variable name passed to a function

前端 未结 17 1979
广开言路
广开言路 2020-11-22 04:11

Let me use the following example to explain my question:

public string ExampleFunction(string Variable) {
    return something;
}

string WhatIsMyName = "         


        
17条回答
  •  太阳男子
    2020-11-22 04:47

    Three ways:

    1) Something without reflection at all:

    GetParameterName1(new { variable });
    
    public static string GetParameterName1(T item) where T : class
    {
        if (item == null)
            return string.Empty;
    
        return item.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
    }
    

    2) Uses reflection, but this is way faster than other two.

    GetParameterName2(new { variable });
    
    public static string GetParameterName2(T item) where T : class
    {
        if (item == null)
            return string.Empty;
    
        return typeof(T).GetProperties()[0].Name;
    }
    

    3) The slowest of all, don't use.

    GetParameterName3(() => variable);
    
    public static string GetParameterName3(Expression> expr)
    {
        if (expr == null)
            return string.Empty;
    
        return ((MemberExpression)expr.Body).Member.Name;
    }
    

    To get a combo parameter name and value, you can extend these methods. Of course its easy to get value if you pass the parameter separately as another argument, but that's inelegant. Instead:

    1)

    public static string GetParameterInfo1(T item) where T : class
    {
        if (item == null)
            return string.Empty;
    
        var param = item.ToString().TrimStart('{').TrimEnd('}').Split('=');
        return "Parameter: '" + param[0].Trim() +
               "' = " + param[1].Trim();
    }
    

    2)

    public static string GetParameterInfo2(T item) where T : class
    {
        if (item == null)
            return string.Empty;
    
        var param = typeof(T).GetProperties()[0];
        return "Parameter: '" + param.Name +
               "' = " + param.GetValue(item, null);
    }
    

    3)

    public static string GetParameterInfo3(Expression> expr)
    {
        if (expr == null)
            return string.Empty;
    
        var param = (MemberExpression)expr.Body;
        return "Parameter: '" + param.Member.Name +
               "' = " + ((FieldInfo)param.Member).GetValue(((ConstantExpression)param.Expression).Value);
    }
    

    1 and 2 are of comparable speed now, 3 is again sluggish.

提交回复
热议问题