【发布时间】:2016-11-02 12:03:52
【问题描述】:
如何获取这个变量名?
var thename = new myclass();
而我想要 myclass 实例中的变量名“thename”?
【问题讨论】:
-
我很好奇这是什么意思?
标签: c#
如何获取这个变量名?
var thename = new myclass();
而我想要 myclass 实例中的变量名“thename”?
【问题讨论】:
标签: c#
您对以下情况有何期望?
var theName = new MyClass();
var otherName = theName;
someList.Add(otherName);
您所使用的名称不属于实例,而是属于引用它的变量。
现在有三个引用指向同一个实例。两个有不同的名字,第三个没有名字。
在 MyClass 对象中,你不知道谁在指着你。堆对象本身总是匿名的。
【讨论】:
someList.Add(new MyClass()); 或您可以使用 Linq 创建对象的各种方式。
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));
当然,不能保证有人没有传入不同的字符串。
【讨论】: