简体   繁体   中英

How To Call Variable Name From Another Class C#

Example of the code

class Main{
        Name Jack = new Name();
        Jack.Speak();
}

class Name{
     public string speak(){
        Console.WriteLine("Hello", valuename);
      }
      
     public Name()
     {
       valuename = nameof(Jack); 
     }
}

Output the what im searching for:

Hello Jack. 

If user types Name Joe = new Name(); output will be Hello Joe.

Local variable names are syntactical sugar that is mostly thrown away by the compiler, so there's no direct way to do this.

The closest you can get is using [CallerArgumentExpression] to have the compiler capture the source code expression that was passed to a parameter, but this only works for method arguments and will capture the entire expression, not just the variable name. For example, the following program will print jack then jack + "hello" :

using System;
using System.Runtime.CompilerServices;

class Program {
    static void Main()
    {
        var jack = "dummy";
        WriteExpression(jack);
        WriteExpression(jack + "hello");
    }

    static void WriteExpression(
        string param, 
        [CallerArgumentExpression("param")] string paramExpression = null
    ) => Console.WriteLine(paramExpression);
}

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