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

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

问题描述

我有一份声明

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

和我想写一个打印功能,这样我整型变量传递给它,$ B $ ; b它打印我的变量名和值

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++?

推荐答案

唯一明智的方法,这样做将是使用表达 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()());
}

请注意:如果这是为了调试的目的,一定要添加 [条件(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天全站免登陆