Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

print name of the variable in c#

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.

eg if i call print(A) it must return "A: 10", and print (B) then it must return "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?

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

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

macro which is there in C/C++?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...