Home > Backend Development > C++ > How Can I Efficiently Retrieve Property Names from Lambda Expressions in C#?

How Can I Efficiently Retrieve Property Names from Lambda Expressions in C#?

Barbara Streisand
Release: 2025-02-01 05:51:09
Original
718 people have browsed it

How Can I Efficiently Retrieve Property Names from Lambda Expressions in C#?

Effectively acquire the attribute name from the Lambda expression

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

form of Lambda expression.
<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>
Copy after login

Actual examples source Expression<Func<TSource, TProperty>>

The following examples demonstrate the usage of this improvement method:

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template