获取变量或参数的名称 [英] get name of a variable or parameter
本文介绍了获取变量或参数的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取变量或参数的名称:
I would like to get the name of a variable or parameter:
例如,如果我有:
var myInput = "input";
var nameOfVar = GETNAME(myInput); // ==> nameOfVar should be = myInput
void testName([Type?] myInput)
{
var nameOfParam = GETNAME(myInput); // ==> nameOfParam should be = myInput
}
我如何在 C# 中做到这一点?
How can I do it in C#?
推荐答案
Pre C# 6.0 解决方案
您可以使用它来获取任何提供的成员的名称:
Pre C# 6.0 solution
You can use this to get a name of any provided member:
public static class MemberInfoGetting
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}
获取变量名:
string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);
获取参数名称:
public class TestClass
{
public void TestMethod(string param1, string param2)
{
string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
}
}
C# 6.0 及更高版本的解决方案
您可以将 nameof 运算符用于参数、变量和属性等:
C# 6.0 and higher solution
You can use the nameof operator for parameters, variables and properties alike:
string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);
这篇关于获取变量或参数的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文