In C#, obtaining variables or parameter names can be implemented through multiple methods.
C# 6.0 Solution:
For the previous version of C# 6.0, you can use the class to retrieve membership name:
MemberInfoGetting
Get variable name:
<code class="language-csharp">public static class MemberInfoGetting { public static string GetMemberName<T>(Expression<Func<T>> memberExpression) { MemberExpression expressionBody = (MemberExpression)memberExpression.Body; return expressionBody.Member.Name; } }</code>
Get parameter name:
<code class="language-csharp">string testVariable = "value"; string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);</code>
C# 6.0 and above solutions:
<code class="language-csharp">public class TestClass { public void TestMethod(string param1, string param2) { string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1); } }</code>
In 6.0 and higher versions, The operational symbol simplifies this process:
The operational character can be used for parameters, variables and attributes. nameof
The above is the detailed content of How Can I Get the Name of a Variable or Parameter in C#?. For more information, please follow other related articles on the PHP Chinese website!