如何获得变量名,如nameof(this)

本文关键字:this 何获得 变量名 nameof | 更新日期: 2023-09-27 18:16:00

如何获得这个变量的名称?

var thename = new myclass();

而我想在myclass实例中的变量名称"thename"?

如何获得变量名,如nameof(this)

在以下场景中您期望什么?

var theName = new MyClass();
var otherName = theName;
someList.Add(otherName);

您所追求的名称不属于实例,而是属于引用它的变量。

现在有三个引用指向同一个实例。两个有不同的名字,第三个没有名字。

在MyClass对象中,你不知道是谁在指向你。堆对象本身总是匿名的。

public class myclass()
{
    public string VariableName { get; set; }
}
var theName = new myclass();
theName.VariableName = nameof(theName);

像这样实例化变量,在创建对象之前,它不存在以具有名称。如果您想强制每个实例填充该变量,那么您可以这样做,但是您的代码会更冗长:

public class myclass()
{
    public myclass(string variableName)
    {
        if (string.IsNullOrWhitespace(variableName)
        {
            throw new ArgumentNullException(nameof(variableName);
        }
        VariableName = variableName;
    }
    public string VariableName { get; private set; }
}
myclass theName;
theName = new myclass(nameof(myclass));

当然,不能保证没有人传入不同的字符串。