如何我可以打印任何对象的名称
MyClass c1, c2;
printName(c1);
printName(c2);
void printName(Object o)
{
Console.WriteLine("name of object : "+ o.???());
}
输出应该是这样的:
name of object : c1
name of object : c2
这是特定的.Net,但回答其他p平台/语言可能会有所帮助。
如何我可以打印任何对象的名称
MyClass c1, c2;
printName(c1);
printName(c2);
void printName(Object o)
{
Console.WriteLine("name of object : "+ o.???());
}
输出应该是这样的:
name of object : c1
name of object : c2
这是特定的.Net,但回答其他p平台/语言可能会有所帮助。
这是不可能的。
变量的名称仅对开发人员非重要(不是编译器或运行时)。
你可以创建一个Dictionary<string, object>
&添加这些实例的变量名称来实现类似的目的。
编辑:这就是它的原因 - 据说 - 编写代码让人们理解和顺带为编译器。
一如既往,请解释什么时候downvoting,为什么? – shahkalpesh 2009-12-09 04:31:28
咦?所以我有这个'Dictionary
@Jason:你说得对。实例被2个变量引用的场景将失败。我回过头来看看OP提供的代码。我把'Dictionary
该名称不存在于源代码之外 - 要做到这一点,您必须将自己作为调试器附加到自己,或者挖掘PDB。总之,对于C#和大多数其他语言而言,这是不切实际的。
这是不可能的。
这是什么结果?
string s = "Hello, world!";
string t = s;
printName(t);
作为s
和t
都指的string
同一实例没有办法与s
作为参数与t
作为参数的printName
调用之间进行区分。
这应该是什么结果?
printName("Hello, world!");
@Jason:请参阅我上面对你的评论的回复。我希望,我说的是感觉:) – shahkalpesh 2009-12-09 04:58:23
我不认为这在理论上是可行的。想想这样的场景:
MyClass a, b;
a = new MyClass();
b = a;
Console.WriteLine("name of b is " + SomeMagicClass.GetVarName(b));
//Should it be "b" or "a"?
我相信有涉及沿变量名甚至不是在运行时出现的线路产生MIDL代码更好的解释。
编辑唉我错了。受Jon Skeet的post的启发,关于Null引用异常处理和突然提醒有关投影,有一种方法可以做到这一点。
下面是完整的工作codez:
public static class ObjectExtensions {
public static string GetVariableName<T>(this T obj) {
System.Reflection.PropertyInfo[] objGetTypeGetProperties = obj.GetType().GetProperties();
if(objGetTypeGetProperties.Length == 1)
return objGetTypeGetProperties[0].Name;
else
throw new ArgumentException("object must contain one property");
}
}
class Program {
static void Main(string[] args) {
string strName = "sdsd";
Console.WriteLine(new {strName}.GetVariableName());
int intName = 2343;
Console.WriteLine(new { intName }.GetVariableName());
}
}
这没有什么原因如下意义:
对象本身是在内存中并没有名字。您正在使用具有名称的引用来访问它。因此,基准名称可以在任何时刻改变,你可以有50个引用“指向”相同的无名对象等
考虑一下:
MyClass c1, c2;
c1 = new MyClass();
c2 = c1;
printName(c1);
printName(c2);
正如你所看到的,C1和C2引用的是完全相同的对象,它没有办法“知道”谁引用它或通过哪个名称。
您需要在MyClass类中放置Name属性,例如。
var c1 = new MyClass() { Name = "c1" };
var c2 = new MyClass() { Name = "c2" };
printName(c1);
printName(c2);
void printName(MyClass o)
{
Console.WriteLine("name of object : "+ o.Name);
}
重复http://stackoverflow.com/questions/729803/print-name-of-the-variable-in-c的 – 2009-12-09 04:30:51
对象:
那么你可以按如下方式使用它没有名字。变量具有名称,变量将_references_保存到对象。此外,两个变量(可能具有不同的名称)可以引用同一个对象。 – 2009-12-09 04:32:12
具体使用哪种语言?我试图重新创建VB.NET,没有运气... – Moshe 2009-12-09 04:32:40