C#框架提供了比较复杂对象的机制,允许推翻特定属性和类型的比较规则.
It is quite common situation when complex objects should be compared. Sometimes objects can contain nested elements, or some members should be excluded from comparison (auto generated identifiers, create/update date etc.), or some members can have custom comparison rules (same data in different formats, like phone numbers). This small framework was developed to solve such kind of problems.
Briefly, Objects Comparer is an object-to-object comparer, which allows to compare objects recursively member by member and define custom comparison rules for certain properties, fields or types.
Objects comparer can be considered as ready to use framework or as a starting point for similar solutions.
Install-Package ObjectsComparer
Let's suppose that we have 2 classes
public class ClassA
{
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public SubClassA SubClass { get; set; }
}
public class SubClassA
{
public bool BoolProperty { get; set; }
}There are some examples below how Objects Comparer can be used to compare instances of these classes.
//Initialize objects and comparer
var a1 = new ClassA { StringProperty = "String", IntProperty = 1 };
var a2 = new ClassA { StringProperty = "String", IntProperty = 1 };
var comparer = new Comparer();
//Compare objects
IEnumerable differences;
var isEqual = comparer.Compare(a1, a2, out differences);
//Print results
Debug.WriteLine(isEqual ? "Objects are equal" : string.Join(Environment.NewLine, differenses));Objects are equal
In examples below Compare objects and Print results blocks will be skipped for brevity except some cases.
var a1 = new ClassA { StringProperty = "String", IntProperty = 1 };
var a2 = new ClassA { StringProperty = "String", IntProperty = 2 };
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='IntProperty', Value1='1', Value2='2'.
var a1 = new ClassA { SubClass = new SubClassA { BoolProperty = true } };
var a2 = new ClassA { SubClass = new SubClassA { BoolProperty = false } };
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='SubClass.BoolProperty', Value1='True', Value2='False'.
var a1 = new StringBuilder("abc");
var a2 = new StringBuilder("abd");
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='', Value1='abc', Value2='abd'.
var a1 = new[] { 1, 2, 3 };
var a2 = new[] { 1, 2, 3 };
var comparer = new Comparer();Objects are equal
var a1 = new[] { 1, 2 };
var a2 = new[] { 1, 2, 3 };
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='Length', Value1='2', Value2='3'.
var a1 = new[] { 1, 2, 3 };
var a2 = new[] { 1, 4, 3 };
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='[1]', Value1='2', Value2='4'.
var a1 = new ArrayList { "Str1", "Str2" };
var a2 = new ArrayList { "Str1", 5 };
var comparer = new Comparer();Difference: DifferenceType=TypeMismatch, MemberPath='[1]', Value1='Str2', Value2='5'.
var a1 = new[] { 1, 2, 3 };
var a2 = new[] { 1, 2, 3 };
var comparer = new Comparer();Objects are equal
var a1 = new HashSet { 1, 2, 3 };
var a2 = new HashSet { 2, 1, 4 };
var comparer = new Comparer();Difference: DifferenceType=MissedElementInSecondObject, MemberPath='', Value1='3', Value2=''. Difference: DifferenceType=MissedElementInFirstObject, MemberPath='', Value1='', Value2='4'.
var a1 = new[] { new[] { 1, 2 } };
var a2 = new[] { new[] { 1, 3 } };
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='[0][1]', Value1='2', Value2='3'.
var a1 = new[] { new[] { 1, 2 } };
var a2 = new[] { new[] { 2, 2 }, new[] { 3, 5 } };
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='Length', Value1='1', Value2='2'.
var a1 = new[] { new[] { 1, 2 }, new[] { 3, 5 } };
var a2 = new[] { new[] { 1, 2 }, new[] { 3, 5, 6 } };
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='[1].Length', Value1='2', Value2='3'.
var a1 = new[,] { { 1, 2 }, { 1, 3 } };
var a2 = new[,] { { 1, 3, 4 }, { 1, 3, 8 } };
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='Dimension1', Value1='2', Value2='3'.
var a1 = new[,] { { 1, 2 } };
var a2 = new[,] { { 1, 3 } };
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='[0,1]', Value1='2', Value2='3'.
C# supports several types of dynamic objects.
dynamic a1 = new ExpandoObject();
a1.Field1 = "A";
a1.Field2 = 5;
a1.Field4 = 4;
dynamic a2 = new ExpandoObject();
a2.Field1 = "B";
a2.Field3 = false;
a2.Field4 = "C";
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.
Difference: DifferenceType=MissedMemberInSecondObject, MemberPath='Field2', Value1='5', Value2=''.
Difference: DifferenceType=TypeMismatch, MemberPath='Field4', Value1='4', Value2='C'.
Difference: DifferenceType=MissedMemberInFirstObject, MemberPath='Field3', Value1='', Value2='False'.
dynamic a1 = new ExpandoObject();
a1.Field1 = "A";
a1.Field2 = 5;
dynamic a2 = new ExpandoObject();
a2.Field1 = "B";
a2.Field3 = false;
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.
Difference: DifferenceType=MissedMemberInSecondObject, MemberPath='Field2', Value1='5', Value2=''.
Difference: DifferenceType=MissedMemberInFirstObject, MemberPath='Field3', Value1='', Value2='False'.
Behavior if member not exists could be changed by providing custom ComparisonSettings (see Comparison Settings below).
dynamic a1 = new ExpandoObject();
a1.Field1 = "A";
a1.Field2 = 0;
dynamic a2 = new ExpandoObject();
a2.Field1 = "B";
a2.Field3 = false;
a2.Field4 = "S";
var comparer = new Comparer(new ComparisonSettings { UseDefaultIfMemberNotExist = true });Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.
Difference: DifferenceType=ValueMismatch, MemberPath='Field4', Value1='', Value2='S'.
Let’s assume that we have such implementation of the DynamicObject class. It is necessary to have a correct implementation of the method GetDynamicMemberNames, otherwise Objects Comparer wouldn't work in a right way.
…dynamic a1 = new DynamicDictionary();
a1.Field1 = "A";
a1.Field3 = true;
dynamic a2 = new DynamicDictionary();
a2.Field1 = "B";
a2.Field2 = 8;
a2.Field3 = 1;
var comparer = new Comparer();Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.
Difference: DifferenceType=TypeMismatch, MemberPath='Field3', Value1='True', Value2='1'.
Difference: DifferenceType=MissedMemberInFirstObject, MemberPath='Field2', Value1='', Value2='8'.
dynamic a1 = new
{
Field1 = "A",
Field2 = 5,
Field3 = true
};
dynamic a2 = new
{
Field1 = "B",
Field2 = 8
};
var comparer = new Comparer();
IEnumerable differences;
var isEqual = comparer.Compare((object)a1, (object)a2, out differences);Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.
Difference: DifferenceType=TypeMismatch, MemberPath='Field2', Value1='5', Value2='8'.
Difference: DifferenceType=MissedMemberInSecondObject, MemberPath='Field3', Value1='True', Value2=''.
This example requires some additional explanations. Types of the objects a1 and a2 were generated by compiler and are considered as the same type if and only if objects a1 and a2 have same set of members (same name and same type). If casting to (object) is skipped in case of different set of members RuntimeBinderException will be thrown.
To override comparison rule we need to create custom value comparer or provide function how to compare objects and how to convert these objects to string(optional) and filter function(optional). Value Comparer should be inherited from AbstractValueComparer or should implement IValueComparer.
public class MyValueComparer: AbstractValueComparer
{
public override bool Compare(string obj1, string obj2, ComparisonSettings settings)
{
return obj1 == obj2; //Implement comparison logic here
}
}Override comparison rule for objects of particular type.
//Use MyComparer to compare all members of type string
comparer.AddComparerOverride(new MyValueComparer());
comparer.AddComparerOverride(typeof(string), new MyValueComparer());
//Use MyComparer to compare all members of type string except members which name starts with "Xyz"
comparer.AddComparerOverride(typeof(string), new MyValueComparer(), member => !member.Name.StartsWith("Xyz"));
comparer.AddComparerOverride(new MyValueComparer(), member => !member.Name.StartsWith("Xyz"));Override comparison rule for particular member (Field or Property).
…Override comparison rule for particular member(s) (Field or Property) by name.
//Use MyValueComparer to compare all members with name equal to "StringProperty"
comparer.AddComparerOverride("StringProperty", new MyValueComparer());Override comparison rule by member filter.
comparer.AddComparerOverride(new MyValueComparer(), m => m.Name == "StringProperty");Overrides by type have highest priority, then overrides by member/member filter and overrides by member name have lowest priority. If more than one value comparers of the same type (by type/by name/by member name) could be applied to the same member, exception AmbiguousComparerOverrideResolutionException will be thrown during comparison.
Example:
var a1 = new ClassA();
var a2 = new ClassA();
comparer.AddComparerOverride(valueComparer1, member => member.Name.StartsWith("String"));
comparer.AddComparerOverride(valueComparer2, member => member.Name.EndsWith("Property"));
var result = comparer.Compare(a1, a2);//Exception hereIgnores members of particular type.
comparer.IgnoreMember();Ignores particular member.
comparer.IgnoreMember(() => new A().TestProperty1);Ignores by member filter.
comparer.IgnoreMember(member => member.Name == "TestProperty1");Ignores particular member by name.
comparer.IgnoreMember("TestProperty1");Comparer constructor has an optional settings parameter to configure some aspects of comparison.
RecursiveComparison
True by default. If true, all members which are not primitive types, do not have custom comparison rule and do not implement ICompareble will be compared using the same rules as root objects.
EmptyAndNullEnumerablesEqual
False by default. If true, empty enumerables (arrays, collections, lists etc.) and null values will be considered as equal values.
UseDefaultIfMemberNotExist
If true and member does not exist, objects comparer will consider that this member is equal to default value of opposite member type. Applicable for dynamic types comparison only. False by default.
Comparison Settings class allows to store custom values that can be used in custom comparers.
SetCustomSetting(T value, string key = null)
GetCustomSetting(string key = null)Factory provides a way to encapsulate comparers creation and configuration. Factory should implement IComparersFactory or should be inherited from ComparersFactory.
public class MyComparersFactory: ComparersFa暂无开放 Issues,或尚未同步最近议题。