print name of the variable in c#

前端 未结 5 1350
小鲜肉
小鲜肉 2020-12-08 17:27

i have a statement

int A = 10,B=6,C=5;

and i want to write a print function such that i pass the int variable to it and it prints me the va

相关标签:
5条回答
  • 2020-12-08 17:40

    The only sensible way to do this would be to use the Expression API; but that changes the code yet further...

    static void Main() {
        int A = 10, B = 6, C = 5;
        Print(() => A);
    }
    static void Print<T>(Expression<Func<T>> expression) {
        Console.WriteLine("{0}={1}",
            ((MemberExpression)expression.Body).Member.Name,
            expression.Compile()());
    }
    

    Note: if this is for debugging purposes, be sure to add [Conditional("DEBUG")] to the method, as using a variable in this way changes the nature of the code in subtle ways.

    0 讨论(0)
  • 2020-12-08 17:43

    You can use lambda expressions:

    static void Main( string[] args ) {
        int A = 50, B = 30, C = 17;
        Print( () => A );
        Print( () => B );
        Print( () => C );
    }
    
    static void Print<T>( System.Linq.Expressions.Expression<Func<T>> input ) {
        System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)input;
        System.Linq.Expressions.MemberExpression member = (System.Linq.Expressions.MemberExpression)lambda.Body;
    
        var result = input.Compile()();
        Console.WriteLine( "{0}: {1}", member.Member.Name, result );
    }
    
    0 讨论(0)
  • 2020-12-08 17:50

    This is not possible without some 'help' from the call site; even reflection does not know about names of local variables.

    0 讨论(0)
  • 2020-12-08 17:50

    This is not possible to do with reflection (see Brian and Joel). In general this is not possible simply because you cannot guarantee a named value is being passed to your print function. For instance, I could just as easily do the following

    print(42);
    print(A + 42);
    

    Neither of these expressions actually has a name. What would you expect to print here?

    0 讨论(0)
  • 2020-12-08 17:51

    Another solution (from a closed post):

    Inspired by Jon Skeet's post about Null Reference exception handling and suddenly being reminded about projection there is a way to kinda do that.

    Here is complete working codez:

    public static class ObjectExtensions {
        public static string GetVariableName<T>(this T obj) {
            System.Reflection.PropertyInfo[] objGetTypeGetProperties = obj.GetType().GetProperties();
    
            if(objGetTypeGetProperties.Length == 1)
                return objGetTypeGetProperties[0].Name;
            else
                throw new ArgumentException("object must contain one property");
        }
    }
    
    class Program {
        static void Main(string[] args) {
            string strName = "sdsd";
            Console.WriteLine(new {strName}.GetVariableName());
    
            int intName = 2343;
            Console.WriteLine(new { intName }.GetVariableName());
        }
    }
    
    0 讨论(0)
提交回复
热议问题