In C#, the method of obtaining variables or parameter names depends on the C#version used.
C# 6.0 The solution before
Before C# 6.0, you can use the method in the
class.
MemberInfoGetting
GetMemberName
Get variable name:
public static string GetMemberName<T>(Expression<Func<T>> memberExpression) => ((MemberExpression)memberExpression.Body).Member.Name;
Get parameter name:
string testVariable = "value"; string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);
<> C# 6.0 and higher version solutions
public class TestClass { public void TestMethod(string param1, string param2) { string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1); } }
C# 6.0 introduced the operator, providing a simple method of acquiring the name:
This method is suitable for variables, parameters and attributes. nameof
The above is the detailed content of How Can I Retrieve Variable and Parameter Names in C#?. For more information, please follow other related articles on the PHP Chinese website!