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

时间:2014-12-17 22:03:28

标签: c#

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

public void Method (string text)
{
     COnsole.WriteLine ( ... + " : " + text ); // should print "myString : hello"
}

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

我想实现这个目标:

Ensure.NotNull (instnce); // should throw: throw new ArgumentNullException ("instance");

有可能吗?是否有来电信息或类似内容?

没有运营商名称?

1 个答案:

答案 0 :(得分:2)

反思的问题是,一旦编译了C#代码,它将不再具有变量名。执行此操作的唯一方法是将变量提升为闭包,但是,您无法从函数中调用它,因为它会在函数中输出新的变量名。这可行:

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;
    }
}

但这不起作用:

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;
    }
}