Extract the attribute name from the Lambda expression
When using the Lambda expression using the name of the passing attribute, retrieving the actual attribute name may be challenging. However, there are some ways to effectively extract this information.
The initial implementation involved the converting Lambda expression into a member expression, assuming the attribute is a string. However, this is only applicable to the string attributes.
In order to solve this problem, a more comprehensive method is needed, which can handle string and non -string attributes at the same time. The following method provides a solution:
<code class="language-csharp">public static PropertyInfo GetPropertyInfo<TSource, TProperty>(
TSource source,
Expression<Func<TSource, TProperty>> propertyLambda)</code>
Copy after login
This method accepts source objects and lambda expressions as input, and returns the PropertyInfo object that indicates the accessable attributes. If the expression does not quote the attribute, it will cause abnormalities.
In the implementation of the method:
It checks whether the text of the Lambda expression is MembeRexpression, and whether the MEMBER is PropertyInfo. If the condition is not met, it will cause abnormalities. -
The Reflecttype of the attribute is matched with the source type or whether it is a subclass of the source type. If not, it will cause abnormalities. -
By using this method, you can securely obtain the PropertyInfo object from the Lambda expression to ensure that the attributes of the interviewed are correct and exist in the target object.
The above is the detailed content of How Can I Retrieve a Property Name from a Lambda Expression in C#?. For more information, please follow other related articles on the PHP Chinese website!