Finding the variable name passed to a function

前端 未结 17 1978
广开言路
广开言路 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:52

    This isn't exactly possible, the way you would want. C# 6.0 they Introduce the nameof Operator which should help improve and simplify the code. The name of operator resolves the name of the variable passed into it.

    Usage for your case would look like this:

    public string ExampleFunction(string variableName) {
        //Construct your log statement using c# 6.0 string interpolation
        return $"Error occurred in {variableName}";
    }
    
    string WhatIsMyName = "Hello World";
    string Hello = ExampleFunction(nameof(WhatIsMyName));
    

    A major benefit is that it is done at compile time,

    The nameof expression is a constant. In all cases, nameof(...) is evaluated at compile-time to produce a string. Its argument is not evaluated at runtime, and is considered unreachable code (however it does not emit an "unreachable code" warning).

    More information can be found here

    Older Version Of C 3.0 and above
    To Build on Nawfals answer

    GetParameterName2(new { variable });
    
    //Hack to assure compiler warning is generated specifying this method calling conventions
    [Obsolete("Note you must use a single parametered AnonymousType When Calling this method")]
    public static string GetParameterName(T item) where T : class
    {
        if (item == null)
            return string.Empty;
    
        return typeof(T).GetProperties()[0].Name;
    }
    

提交回复
热议问题