简体   繁体   中英

CallerInfo, get name of variable passed to method (like nameof)

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

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

Is it possible to get name of variable passed to a method?

I want to achieve this:

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

Is it possible? WIth caller info or something similiar?

Without nameof operator?

Problem with reflection is that, once the C# code is compiled, it will no longer have the variable names. The only way to do this is to promote the variable to a closure, however, you wouldn't be able to call it from a function like you are doing because it would output the new variable name in your function. This would work:

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

This would NOT work though:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM