從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中文網其他相關文章!