在c#中打印变量的名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/729803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
print name of the variable in c#
提问by Anirudh Goel
i have a statement
我有一个声明
int A = 10,B=6,C=5;
and i want to write a print function such that i pass the int variable to it and it prints me the variable name and the value.
并且我想编写一个打印函数,以便我将 int 变量传递给它,它会向我打印变量名称和值。
eg if i call print(A) it must return "A: 10", and print (B) then it must return "B:6"
例如,如果我调用 print(A) 它必须返回“A: 10”,而 print (B) 那么它必须返回“B:6”
in short i want to know how can i access the name of the variable and print it to string in c#. DO i have to use reflection?
简而言之,我想知道如何访问变量的名称并将其打印为 C# 中的字符串。我必须使用反射吗?
After reading the answers
阅读答案后
Hi all, thanks for the suggestions provided. I shall try them out, however i wanted to know if it is at all possible in .NET 2.0? Nothing similar to
大家好,感谢提供的建议。我会尝试一下,但是我想知道在 .NET 2.0 中是否有可能?没有类似的
#define prt(x) std::cout << #x " = '" << x << "'" << std::endl;
macro which is there in C/C++?
C/C++ 中有哪些宏?
采纳答案by Marc Gravell
The only sensible way to do this would be to use the Expression
API; but that changes the code yet further...
唯一明智的方法是使用Expression
API;但这进一步改变了代码......
static void Main() {
int A = 10, B = 6, C = 5;
Print(() => A);
}
static void Print<T>(Expression<Func<T>> expression) {
Console.WriteLine("{0}={1}",
((MemberExpression)expression.Body).Member.Name,
expression.Compile()());
}
Note: if this is for debugging purposes, be sure to add [Conditional("DEBUG")]
to the method, as using a variable in this way changes the nature of the code in subtle ways.
注意:如果这是出于调试目的,请务必添加[Conditional("DEBUG")]
到方法中,因为以这种方式使用变量会以微妙的方式改变代码的性质。
回答by Brian
This is not possible without some 'help' from the call site; even reflection does not know about names of local variables.
如果没有呼叫站点的一些“帮助”,这是不可能的;甚至反射也不知道局部变量的名称。
回答by JaredPar
This is not possible to do with reflection (see Brian and Joel). In general this is not possible simply because you cannot guarantee a named value is being passed to your print function. For instance, I could just as easily do the following
这不可能与反射有关(参见 Brian 和 Joel)。一般来说,这是不可能的,因为您不能保证将命名值传递给您的打印函数。例如,我可以轻松地执行以下操作
print(42);
print(A + 42);
Neither of these expressions actually has a name. What would you expect to print here?
这些表达式实际上都没有名称。您希望在这里打印什么?
回答by TcKs
You can use lambda expressions:
您可以使用 lambda 表达式:
static void Main( string[] args ) {
int A = 50, B = 30, C = 17;
Print( () => A );
Print( () => B );
Print( () => C );
}
static void Print<T>( System.Linq.Expressions.Expression<Func<T>> input ) {
System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)input;
System.Linq.Expressions.MemberExpression member = (System.Linq.Expressions.MemberExpression)lambda.Body;
var result = input.Compile()();
Console.WriteLine( "{0}: {1}", member.Member.Name, result );
}
回答by Igor Zevaka
Another solution (from a closed post):
另一个解决方案(来自封闭的帖子):
Inspired by Jon Skeet's postabout Null Reference exception handling and suddenly being reminded about projection there is a way to kinda do that.
受 Jon Skeet关于 Null Reference 异常处理的帖子的启发,突然想起投影,有一种方法可以做到这一点。
Here is complete working 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());
}
}