In C#, access to variables or parameters names are very important for various scenarios, such as error processing and dynamic code generation. Let's discuss how to achieve this:
C# 6.0 Solution:
Before C# 6.0, the solution to obtain the name of the member is to use reflection. Considering the following category, it provides a generic method for searching the name of the member:
To use this method, you can pass a lambda expression that reference variables or parameters of this expression:
<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>
C# 6.0 and higher version solutions:
<code class="language-csharp">string testVariable = "value"; string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);</code>
In C# 6.0 and higher versions, The operator provides a more concise and more efficient method of acquiring member names:
This operational symbol can be used for parameters, variables, and attributes: nameof
The above is the detailed content of How Can I Get the Name of a C# Variable or Parameter?. For more information, please follow other related articles on the PHP Chinese website!