所以,这可行:
课程:
public class c_entry
{
public string Name { get; private set; }
public c_entry(string name)
{
Name = name;
}
}
创建实例并将变量名称作为参数发送
public void method()
{
c_entry c = new c_entry(nameof(c));
}
但是我真正想做的就是通过从类内部引用实例Name
来设置name
,所以我不必传递nameof(instance)
作为参数
public class c_entry
{
public string Name { get; private set; }
public c_entry()
{
Name = nameof(this); // This line won't compile because "this" expression doesn't have a name
}
}
我认为这不可能-但是吗?
答案 0 :(得分:4)
不,您不能,因为这没有道理。实例没有单个名称。
var x = new YourClass(); // you might think this is named x
new YourClass(); // what's the name now? okay, maybe name should be nullable?
var x = new YourClass();
var y = x; // and now?
// What name should the single instance have now?
// should each instance have a list of names?