This is a cursory question I can't quite answer.
The main program
class Program{
static void Main(string[] args){
Console.WriteLine("Begin");
var myClass = new MyClass();
Util.Print(myClass.Id);
Util.Print(myClass.Server);
Util.Print(myClass.Ping);
Console.WriteLine("End");
}
}
How do I implement the Util.Print method to get this output to the console:
Begin
Id
Server
Ping
End
Assuming you don't want to use strings, the most common answer is via an Expression
- essentially emulating the missing infoof
; you would have to use something like:
Console.WriteLine("Begin");
var myClass = new MyClass();
Util.Print(() => myClass.Id);
Util.Print(() => myClass.Server);
Util.Print(() => myClass.Ping);
Console.WriteLine("End");
Assuming they are all properties/fields (edit added method-call support):
public static class Util
{
public static void Print<T>(Expression<Func<T>> expr)
{
WriteExpression(expr);
}
public static void Print(Expression<Action> expr) // for "void" methods
{
WriteExpression(expr);
}
private static void WriteExpression(Expression expr)
{
LambdaExpression lambda = (LambdaExpression)expr;
switch (lambda.Body.NodeType)
{
case ExpressionType.MemberAccess:
Console.WriteLine(((MemberExpression)lambda.Body)
.Member.Name);
break;
case ExpressionType.Call:
Console.WriteLine(((MethodCallExpression)lambda.Body)
.Method.Name);
break;
default:
throw new NotSupportedException();
}
}
}
In addition to Marc's answer: here is an article which explains several ways to do what you want to do (one such method uses expressions).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With