C# CallerInfo,获取传递给方法的变量的名称(如nameof)

C# CallerInfo,获取传递给方法的变量的名称(如nameof),c#,C#,是否可以获取传递给方法的变量的名称 我想做到这一点: public void Test () { string myString = "hello"; } public void Method (string text) { COnsole.WriteLine ( ... + " : " + text ); // should print "myString : hello" } 可能吗?有来电信息还是类似的 没有nameof操作符?反射的问题是,一旦编译了C代码,它将不再

是否可以获取传递给方法的变量的名称

我想做到这一点:

public void Test ()
{
    string myString = "hello";
}

public void Method (string text)
{
     COnsole.WriteLine ( ... + " : " + text ); // should print "myString : hello"
}
可能吗?有来电信息还是类似的


没有nameof操作符?

反射的问题是,一旦编译了C代码,它将不再具有变量名。唯一的方法是将变量升级为闭包,但是,您不能像现在这样从函数中调用它,因为它会在您的函数中输出新的变量名。这将有助于:

Ensure.NotNull (instnce); // should throw: throw new ArgumentNullException ("instance");
使用系统;
使用System.Linq.Expressions;
公共课程
{
公共静态void Main()
{
string myString=“我的Hello字符串变量”;
//打印“myString:MyHello字符串变量”
WriteLine(“{0}:{1}”,GetVariableName(()=>myString),myString);
}
公共静态字符串GetVariableName(表达式表达式)
{
var body=(MemberExpression)expr.body;
返回body.Member.Name;
}
}
但这不起作用:

using System;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        string myString = "My Hello string variable";

        // Prints "myString : My Hello String Variable
        Console.WriteLine("{0} : {1}", GetVariableName(() => myString), myString);
    }

    public static string GetVariableName<T>(Expression<Func<T>> expr)
    {
        var body = (MemberExpression)expr.Body;

        return body.Member.Name;
    }
}
使用系统;
使用System.Linq.Expressions;
公共课程
{
公共静态void Main()
{
字符串myString=“test”;
//这将打印“myVar:test”
方法(myString);
}
公共静态无效方法(字符串myVar)
{
WriteLine(“{0}:{1}”,GetVariableName(()=>myVar),myVar);
}
公共静态字符串GetVariableName(表达式表达式)
{
var body=(MemberExpression)expr.body;
返回body.Member.Name;
}
}

这是完全不可能的。您可以将调用站点更改为滥用表达式树。这看起来像是巨大的开销(x-),谢谢。
using System;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        string myString = "test";

        // This will print "myVar : test"
        Method(myString);
    }

    public static void Method(string myVar)
    {
        Console.WriteLine("{0} : {1}", GetVariableName(() => myVar), myVar);
    }

    public static string GetVariableName<T>(Expression<Func<T>> expr)
    {
        var body = (MemberExpression)expr.Body;

        return body.Member.Name;
    }
}