首頁 > 後端開發 > C++ > 如何從C#中的lambda表達式中有效地檢索屬性名稱?

如何從C#中的lambda表達式中有效地檢索屬性名稱?

Barbara Streisand
發布: 2025-02-01 05:51:09
原創
718 人瀏覽過

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

從Lambda表達式中高效獲取屬性名稱

在C#中,通過Lambda表達式傳遞屬性名稱通常比較棘手,尤其當屬性以字符串形式表示時。一種常見的解決方法是將Lambda表達式轉換為成員表達式,但這僅適用於字符串屬性。

改進方案

為了克服現有方法的局限性,我們提出一種通用的方法,該方法返回指定表達式的PropertyInfo對象。如果表達式不代表屬性,則拋出異常。

<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>
登入後複製

此方法使用source參數進行類型推斷,並接受Expression<Func<TSource, TProperty>>形式的Lambda表達式。

實際示例

以下示例演示了此改進方法的用法:

<code class="language-csharp">var propertyInfo = GetPropertyInfo(someUserObject, u => u.UserID);</code>
登入後複製

此方法提供了一種更健壯和通用的方式來從Lambda表達式中提取屬性信息。

以上是如何從C#中的lambda表達式中有效地檢索屬性名稱?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板