在c#中打印变量的名称
我有一个声明
int A = 10,B=6,C=5;
我想写一个打印函数,以便我将int变量传递给它,它会打印变量名称和值。
例如,如果我打印(A)它必须返回“A:10”,然后打印(B)然后它必须返回“B:6”
总之,我想知道如何访问变量的名称并将其打印到c#中的字符串。 我必须使用reflection吗?
看完答案后
大家好,感谢您提供的建议。 我会尝试一下,但我想知道它是否在.NET 2.0中完全可能? 没什么相似的
#define prt(x) std::cout << #x " = '" << x << "'" << std::endl;
在C / C ++中有哪些宏?
唯一明智的方法是使用Expression
API; 但这进一步改变了代码……
static void Main() { int A = 10, B = 6, C = 5; Print(() => A); } static void Print(Expression> expression) { Console.WriteLine("{0}={1}", ((MemberExpression)expression.Body).Member.Name, expression.Compile()()); }
注意:如果这是出于调试目的,请确保将[Conditional("DEBUG")]
到方法中,因为以这种方式使用变量会以微妙的方式更改代码的性质。
您可以使用lambda表达式:
static void Main( string[] args ) { int A = 50, B = 30, C = 17; Print( () => A ); Print( () => B ); Print( () => C ); } static void Print( System.Linq.Expressions.Expression> input ) { System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)input; System.Linq.Expressions.MemberExpression member = (System.Linq.Expressions.MemberExpression)lambda.Body; var result = input.Compile()(); Console.WriteLine( "{0}: {1}", member.Member.Name, result ); }
没有来自呼叫站点的一些“帮助”,这是不可能的; 甚至reflection都不知道局部变量的名称。
这与reflection无法做到(见Brian和Joel)。 通常,这是不可能的,因为您无法保证将命名值传递给您的打印function。 例如,我可以轻松地执行以下操作
print(42); print(A + 42);
这些表达式实际上都没有名称。 你期望在这里打印什么?
另一种解决方案(来自封闭的post ):
灵感来自Jon Skeet关于Null Referenceexception处理的post ,并突然被提醒有关投影,有一种方法可以做到这一点。
这是完整的工作代码:
public static class ObjectExtensions { public static string GetVariableName(this T obj) { System.Reflection.PropertyInfo[] objGetTypeGetProperties = obj.GetType().GetProperties(); if(objGetTypeGetProperties.Length == 1) return objGetTypeGetProperties[0].Name; else throw new ArgumentException("object must contain one property"); } } class Program { static void Main(string[] args) { string strName = "sdsd"; Console.WriteLine(new {strName}.GetVariableName()); int intName = 2343; Console.WriteLine(new { intName }.GetVariableName()); } }
在未来,我们只使用nameof运算符。
- 如何在Kendo Grid MVC中将列宽设置为自动调整
- 异步任务’堵塞’
- 带有C#和Apache NMS的ActiveMQ – 计算队列中的消息
- C#创建类的实例并按字符串中的名称设置属性
- Microsoft Enterprise Library类型加载exception无法加载Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer
- 有没有办法以编程方式检查飞机模式状态?
- 检查WebAPI是否可用于C#Code Behind的简单,最佳方法
- 将类型限制为Int,Double,long 的generics
- 如何在表单中打开表单?