在c#中打印变量的名称 [英] print name of the variable in c#

查看:68
本文介绍了在c#中打印变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个声明

int A = 10,B=6,C=5;

并且我想编写一个打印函数,以便将 int 变量传递给它,然后它向我打印了变量名称和值.

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.

例如,如果我调用 print(A)它必须返回A:10",并打印(B)然后它必须返回B:6"

eg if i call print(A) it must return "A: 10", and print (B) then it must return "B:6"

简而言之,我想知道如何访问变量的名称并将其打印为 c# 中的字符串.我必须使用反射吗?

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?

阅读答案后

大家好,感谢您提供的建议.我会尝试一下,但是我想知道在 .NET 2.0 中是否有可能?没有类似的

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

#define prt(x) std::cout << #x " = '" << x << "'" << std::endl;

C/C++ 中有哪些宏?

macro which is there in C/C++?

推荐答案

唯一明智的方法是使用 Expression API;但这进一步改变了代码......

The only sensible way to do this would be to use the Expression API; but that changes the code yet further...

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()());
}

注意:如果这是出于调试目的,请务必在方法中添加[Conditional("DEBUG")],因为以这种方式使用变量会微妙地改变代码的性质方式.

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.

这篇关于在c#中打印变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆