Home >Backend Development >C++ >How Can I Efficiently Retrieve Property Names from Lambda Expressions in C#?
In C#, the name of the attribute name of the transmission of the Lambda expression is usually tricky, especially when the attribute is represented by a string. A common solution is to convert Lambda expressions into member expressions, but this is only applicable to string attributes.
Improvement plan
In order to overcome the limitations of existing methods, we propose a common method that returns the object of specified expression. If the expression does not represent attributes, it is thrown out of an exception.
PropertyInfo
This method uses the parameter for type inference, and accepts the
<code class="language-csharp">public static PropertyInfo GetPropertyInfo<TSource, TProperty>( TSource source, Expression<Func<TSource, TProperty>> propertyLambda) { if (propertyLambda.Body is not MemberExpression member) { throw new ArgumentException(string.Format( "表达式 '{0}' 指向方法,而非属性。", propertyLambda.ToString())); } if (member.Member is not PropertyInfo propInfo) { throw new ArgumentException(string.Format( "表达式 '{0}' 指向字段,而非属性。", propertyLambda.ToString())); } Type type = typeof(TSource); if (propInfo.ReflectedType != null && type != propInfo.ReflectedType && !type.IsSubclassOf(propInfo.ReflectedType)) { throw new ArgumentException(string.Format( "表达式 '{0}' 指向的属性不属于类型 {1}。", propertyLambda.ToString(), type)); } return propInfo; }</code>
Actual examples source
Expression<Func<TSource, TProperty>>
This method provides a more robust and general way to extract attribute information from the Lambda expression.
The above is the detailed content of How Can I Efficiently Retrieve Property Names from Lambda Expressions in C#?. For more information, please follow other related articles on the PHP Chinese website!