Home >Backend Development >C++ >How Can I Get a Property's Name as a String in C#?
In C# 6.0 and above, you can use the nameof
expression to conveniently get the property name as a string. This expression resolves to the name of the property at compile time.
Example:
<code class="language-csharp">string propertyName = nameof(SomeClass.SomeProperty);</code>
This expression evaluates to "SomeProperty" at compile time.
Note: nameof
can only be used for attributes, not for members of other types.
Early version of C#
In versions prior to C# 6.0, you can use the following method:
<code class="language-csharp">public string GetPropertyName<T>(Expression<Func<T>> propertyLambda) { var memberExpression = propertyLambda.Body as MemberExpression; if (memberExpression == null) throw new ArgumentException("表达式必须是属性lambda表达式。"); return memberExpression.Member.Name; }</code>
This method takes a lambda expression representing a property accessor and returns the name of the property.
Example:
<code class="language-csharp">string propertyName = GetPropertyName(() => SomeClass.SomeProperty);</code>
The above is the detailed content of How Can I Get a Property's Name as a String in C#?. For more information, please follow other related articles on the PHP Chinese website!