我想获取变量或参数的名称:
例如,如果我有:
var myInput = "input"; var nameOfVar = GETNAME(myInput); // ==> nameOfVar should be = myInput void testName([Type?] myInput) { var nameOfParam = GETNAME(myInput); // ==> nameOfParam should be = myInput }
如何在C#中做到这一点?
您可以使用它来获取任何提供的成员的名称:
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); } }
您可以对参数,变量和属性使用nameof运算符:
string testVariable = "value"; string nameOfTestVariable = nameof(testVariable);