简体   繁体   English

如何从另一个 Class C# 调用变量名

[英]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: Output 我正在搜索的内容:

Hello Jack. 

If user types Name Joe = new Name();如果用户键入Name Joe = new Name(); output will be Hello Joe. output 将是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.最接近的方法是使用[CallerArgumentExpression]让编译器捕获传递给参数的源代码表达式,但这仅适用于方法 arguments 并且将捕获整个表达式,而不仅仅是变量名。 For example, the following program will print jack then jack + "hello" :例如,以下程序将打印jack然后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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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