.net 我正在使用NuGet包CompareNetObjects来获取两个相同类型的复杂对象之间的差异,

oknrviil  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(206)

下面是我尝试完成的一个示例

CompareLogic compareLogic = new CompareLogic();
compareLogic.Config.MaxDifferences = int.MaxValue;
compareLogic.Config.ShowBreadcrumb = false;

MyType originalData;
MyType newData;

ComparisonResult myComparison = compareLogic.Compare(originalData, newData);

var differences = myComparison.Differences;

MyType changedData = differences.????
ddrv8njm

ddrv8njm1#

您可以执行某些操作like the following

//  Example extended from
//  https://github.com/GregFinzer/Compare-Net-Objects/wiki/Getting-Started

//  This is the comparison class
CompareLogic compareLogic = new CompareLogic();

//  Create a couple objects to compare
Person person1 = new Person();
person1.DateCreated = DateTime.Now;
person1.Name = "Greg";

Person person2 = new Person();
person2.Name = "John";
person2.DateCreated = person1.DateCreated + TimeSpan.FromSeconds(1);

compareLogic.Config.MaxDifferences = 2;  //  not just one
ComparisonResult result = compareLogic.Compare(expectedObject: person1, actualObject: person2);

//  These will be different, write out the differences
if (!result.AreEqual)
{
    Console.WriteLine(result.DifferencesString);

    foreach(var diff in result.Differences)
    {
        Console.WriteLine($"PropertyName:  {diff.PropertyName}");
        Console.WriteLine($"ActualName:    {diff.ActualName}");
        Console.WriteLine($"ExpectedName:  {diff.ExpectedName}");
        Console.WriteLine($"Object1 value: {diff.Object1Value}   expectedObject");
        Console.WriteLine($"Object1 type:  {diff.Object1TypeName}");
        Console.WriteLine($"Object2 value: {diff.Object2Value}   actualObject");
        Console.WriteLine($"Object2 type:  {diff.Object2TypeName}");
        Console.WriteLine("");
    }
}

结果输出:

Begin Differences (2 differences):
Types [String,String], Item Expected.Name != Actual.Name, Values (Greg,John)
Types [DateTime,DateTime], Item Expected.DateCreated != Actual.DateCreated, Values (17.11.2022 20:41:51,17.11.2022 20:41:52)
End Differences (Maximum of 2 differences shown).
PropertyName:  Name
ActualName:    Actual
ExpectedName:  Expected
Object1 value: Greg   expectedObject
Object1 type:  String
Object2 value: John   actualObject
Object2 type:  String

PropertyName:  DateCreated
ActualName:    Actual
ExpectedName:  Expected
Object1 value: 17.11.2022 20:41:51   expectedObject
Object1 type:  DateTime
Object2 value: 17.11.2022 20:41:52   actualObject
Object2 type:  DateTime

相关问题