这里在判断器集合中,实现类的其实是有顺序的,StructEquality必须要放到ValueTypeEquality的前面,因为Struct也是值类型,如果不放到最前面,会导致判断失败。
创建判断器入口类 public class ObjectEquality { public bool IsEqual(object source, object target) { if (source.GetType() != target.GetType()) { return false; } if (source == null && target == null) { return true; } else if (source == null && target != null) { return false; } else if (source != null && target == null) { return false; } var equality = EqualityCollection.Equalities .First(p => p.MatchCondition(source)); return equality.IsEqual(source, target); } }前面所有实现类的访问级别都是Internal, 所以我们需要创建一个判断器入口类, 外部只能通过ObjectEquality类的实例来实现判断相等。
最终效果下面我列举几个测试用例,看看效果是不是我们想要的
对比Struct public struct DemoStruct { public int Id { get; set; } public string Name { get; set; } } var a = new DemoStruct(); a.Id = 1; a.Name = "Test"; var b = new DemoStruct(); b.Id = 1; b.Name = "Test"; var c = new DemoStruct(); b.Id = 2; b.Name = "Test"; ObjectEquality objectEquality = new ObjectEquality(); objectEquality.IsEqual(a,b); //true objectEquality.IsEqual(a,c); //false 对比类 public class SimpleClass { public int Id { get; set; } public string Name { get; set; } } var a = new SimpleClass { Id = 1, Name = "A" }; var b = new SimpleClass { Id = 1, Name = "A" }; var c = new SimpleClass { Id = 2, Name = "A" }; ObjectEquality objectEquality = new ObjectEquality(); objectEquality.IsEqual(a,b); //true objectEquality.IsEqual(a,c); //false 对比数组 var a = new int[] { 1, 2, 3 }; var b = new int[] { 1, 2, 3 }; var c = new int[] { 1, 1, 2 }; ObjectEquality objectEquality = new ObjectEquality(); objectEquality.IsEqual(a,b); //true objectEquality.IsEqual(a,c); //false