如何高效的比较两个 Object 对象是否相等?
咨詢區(qū)
DmitryBoyko:
我有兩個(gè)復(fù)雜的對(duì)象 Object1 和 Object2,這兩個(gè)對(duì)象大概有 5 層的深度。
我現(xiàn)在需要一個(gè)快速的方法比較兩個(gè)對(duì)象是否相等,請(qǐng)問我該如何實(shí)現(xiàn)?
回答區(qū)
vivek nuna:
如果你的class是一個(gè)不可變的,比如說它下面的屬性是那種一創(chuàng)建之后就不會(huì)再變更的情況,同時(shí)又是 C#9 的話,我建議你使用一個(gè)叫 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:
可以通過序列化的方式來比較兩個(gè) object 是否相等,如果要這么做的話,可以使用擴(kuò)展方法來實(shí)現(xiàn),參考如下代碼:
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:
可以通過反射對(duì)類中的所有屬性進(jìn)行比較,參考如下代碼:
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;}點(diǎn)評(píng)區(qū)
在現(xiàn)實(shí)項(xiàng)目開發(fā)中,很多時(shí)候你無法對(duì) class 進(jìn)行操控,比如說,不能給它實(shí)現(xiàn)個(gè)什么 IEquatable<T> 接口,也不能重寫它的 Equals() 和 Override() 方法,所以說用 序列化 的方式進(jìn)行比較還是比較簡(jiǎn)單粗暴的。
總結(jié)
以上是生活随笔為你收集整理的如何高效的比较两个 Object 对象是否相等?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Exceptionless服务端+kib
- 下一篇: dotnet 使用 Infer# 自动分