在 C# 中高效率比較物件屬性
本文探討了在 C# 中比較物件屬性的有效方法。 一個常見的挑戰是確定同一類型的兩個物件是否具有相同的屬性值。 我們將研究一種利用 LINQ 和擴展方法的改進方法。
增強的屬性比較方法
以下 C# 程式碼提供了比較物件屬性的改進解決方案:
<code class="language-csharp">public static bool PublicInstancePropertiesEqual<T>(this T self, T to, params string[] ignore) where T : class { if (self != null && to != null) { var type = typeof(T); var ignoreList = new List<string>(ignore); var unequalProperties = from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance) where !ignoreList.Contains(pi.Name) && pi.GetUnderlyingType().IsSimpleType() && pi.GetIndexParameters().Length == 0 let selfValue = type.GetProperty(pi.Name).GetValue(self, null) let toValue = type.GetProperty(pi.Name).GetValue(to, null) where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue)) select selfValue; return !unequalProperties.Any(); } return self == to; }</code>
此方法提供了幾個關鍵改進:
for
循環相比,LINQ 的使用簡化了屬性迭代,增強了可讀性並可能提高效能。 int
、string
、bool
),防止處理複雜物件屬性時出現潛在錯誤。 這避免了遞迴問題。 這種最佳化方法可確保物件屬性的高效可靠比較,同時保持清晰度和易用性。
以上是如何在 C# 中有效比較物件屬性是否相等?的詳細內容。更多資訊請關注PHP中文網其他相關文章!