假设您不想使用字符串,最常见的答案是通过Expression
- 基本上模拟缺失infoof
; 你必须使用类似的东西:
Console.WriteLine("Begin"); var myClass = new MyClass(); Util.Print(() => myClass.Id); Util.Print(() => myClass.Server); Util.Print(() => myClass.Ping); Console.WriteLine("End");
假设它们都是属性/字段(编辑添加的方法调用支持):
public static class Util { public static void Print(Expression > expr) { WriteExpression(expr); } public static void Print(Expression 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(); } } }