查看DeepEqual的源代码,该库允许通过IComparison
界面进行自定义比较。有了这个,我模拟了您需要的模型:
public class MyClass
{
public MyClass()
{
MyList = new List<MySubClass>(new[]
{
new MySubClass {Id = Guid.Parse("1".PadLeft(32, '0')), Name = "Foo"},
new MySubClass {Id = Guid.Parse("2".PadLeft(32, '0')), Name = "Bar"},
new MySubClass {Id = Guid.Parse("3".PadLeft(32, '0')), Name = "Test"},
});
}
public MyClass(params MySubClass[] subs)
{
MyList = new List<MySubClass>(subs);
}
public List<MySubClass> MyList { get; set; }
}
public class MySubClass
{
public Guid Id { get; set; }
public string Name { get; set; }
}
然后我继续创建一个自定义IComparison
类:
public class MySubClassComparer : IComparison
{
public bool CanCompare(Type type1, Type type2)
{
return type1 == type2 && type1 == typeof(MySubClass);
}
public (ComparisonResult result, IComparisonContext context) Compare(IComparisonContext context, object value1, object value2)
{
if (value1 is MySubClass first && value2 is MySubClass second)
{
if (first.Name == second.Name)
{
return (ComparisonResult.Pass, context);
}
}
return (ComparisonResult.Fail, context);
}
}
这是我通过的两个单元测试:
[Fact]
public void IsDeepEqual_ShouldReturnTrue_WhenListHasSameNames()
{
// Arrange
MyClass sut = new MyClass();
MyClass parameter = new MyClass(new[]
{
new MySubClass {Id = Guid.Parse("4".PadLeft(32, '0')), Name = "Foo"},
new MySubClass {Id = Guid.Parse("5".PadLeft(32, '0')), Name = "Bar"},
new MySubClass {Id = Guid.Parse("6".PadLeft(32, '0')), Name = "Test"},
});
var comparer = new ComparisonBuilder().WithCustomComparison(new MySubClassComparer()).Create();
// Act
bool result = sut.IsDeepEqual(parameter, comparer);
// Assert
Assert.True(result);
}
[Fact]
public void IsDeepEqual_ShouldReturnFalse_WhenListHasDifferentNames()
{
// Arrange
MyClass sut = new MyClass();
MyClass parameter = new MyClass(new[]
{
new MySubClass {Id = Guid.Parse("4".PadLeft(32, '0')), Name = "Foo"},
new MySubClass {Id = Guid.Parse("5".PadLeft(32, '0')), Name = "Bar"},
new MySubClass {Id = Guid.Parse("6".PadLeft(32, '0')), Name = "Fail"},
});
var comparer = new ComparisonBuilder().WithCustomComparison(new MySubClassComparer()).Create();
// Act
bool result = sut.IsDeepEqual(parameter, comparer);
// Assert
Assert.False(result);
}
备注
此比较应忽略该Id
属性,但不确定这是否是完成任务的最佳方式。有一个IgnoreProperty方法可能更适合该任务,但目前看不到让它工作的方法。
如果有人比我对图书馆有更多的经验,请让我知道更好的方法,我会相应地更新我的答案。