如何高效的比较两个 Object 对象是否相等?
生活随笔
收集整理的這篇文章主要介紹了
如何高效的比较两个 Object 对象是否相等?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
咨詢區
DmitryBoyko:
我有兩個復雜的對象 Object1 和 Object2,這兩個對象大概有 5 層的深度。
我現在需要一個快速的方法比較兩個對象是否相等,請問我該如何實現?
回答區
vivek nuna:
如果你的class是一個不可變的,比如說它下面的屬性是那種一創建之后就不會再變更的情況,同時又是 C#9 的話,我建議你使用一個叫 record 的新特性,參考如下代碼:
public?record?Person {public?string?LastName?{?get;?}public?string?FirstName?{?get;?}public?Person(string?first,?string?last)?=>?(FirstName,?LastName)?=?(first,?last); }var?person1?=?new?Person("Bill",?"Wagner"); var?person2?=?new?Person("Bill",?"Wagner");Console.WriteLine(person1?==?person2);?//?trueArvo Bowen:
可以通過序列化的方式來比較兩個 object 是否相等,如果要這么做的話,可以使用擴展方法來實現,參考如下代碼:
using?System.IO; using?System.Xml.Serialization;static?class?ObjectHelpers {public?static?string?SerializeObject<T>(this?T?toSerialize){XmlSerializer?xmlSerializer?=?new?XmlSerializer(toSerialize.GetType());using?(StringWriter?textWriter?=?new?StringWriter()){xmlSerializer.Serialize(textWriter,?toSerialize);return?textWriter.ToString();}}public?static?bool?EqualTo(this?object?obj,?object?toCompare){if?(obj.SerializeObject()?==?toCompare.SerializeObject())return?true;elsereturn?false;}public?static?bool?IsBlank<T>(this?T?obj)?where?T:?new(){T?blank?=?new?T();T?newObj?=?((T)obj);if?(newObj.SerializeObject()?==?blank.SerializeObject())return?true;elsereturn?false;}}然后像下面這樣使用。
if?(record.IsBlank())throw?new?Exception("Record?found?is?blank.");if?(record.EqualTo(new?record()))throw?new?Exception("Record?found?is?blank.");goric:
可以通過反射對類中的所有屬性進行比較,參考如下代碼:
static?bool?Compare<T>(T?Object1,?T?object2){//Get?the?type?of?the?objectType?type?=?typeof(T);//return?false?if?any?of?the?object?is?falseif?(object.Equals(Object1,?default(T))?||?object.Equals(object2,?default(T)))return?false;//Loop?through?each?properties?inside?class?and?get?values?for?the?property?from?both?the?objects?and?compareforeach?(System.Reflection.PropertyInfo?property?in?type.GetProperties()){if?(property.Name?!=?"ExtensionData"){string?Object1Value?=?string.Empty;string?Object2Value?=?string.Empty;if?(type.GetProperty(property.Name).GetValue(Object1,?null)?!=?null)Object1Value?=?type.GetProperty(property.Name).GetValue(Object1,?null).ToString();if?(type.GetProperty(property.Name).GetValue(object2,?null)?!=?null)Object2Value?=?type.GetProperty(property.Name).GetValue(object2,?null).ToString();if?(Object1Value.Trim()?!=?Object2Value.Trim()){return?false;}}}return?true;}點評區
在現實項目開發中,很多時候你無法對 class 進行操控,比如說,不能給它實現個什么 IEquatable<T> 接口,也不能重寫它的 Equals() 和 Override() 方法,所以說用 序列化 的方式進行比較還是比較簡單粗暴的。
總結
以上是生活随笔為你收集整理的如何高效的比较两个 Object 对象是否相等?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Exceptionless服务端+kib
- 下一篇: dotnet 使用 Infer# 自动分