首页 > 解决方案 > 如何在记录类型中查找更改的属性名称和值?

问题描述

创建记录类型。

public record Animal
{
  public string Name{ get; init; }
  public string Type{ get; init; }
  public string Genus{ get; init; }
  public string Owner { get; init; }
}

var cat= new Animal
{
  Name = "FluffyCat",
  Type = "Feline",
  Genus = "Mammal",
  Owner = "Agent Smith"
 
};

克隆并更改一些值。

var newCat = cat with
            { Name = "AngryCat", Owner= "Morpheus" };

我们可以很容易地测试相等性

Console.WriteLine(newCat.Equals(cat));

如何在不比较每个属性值的情况下找到更改的属性名称?

标签: c#c#-9.0c#-record-type

解决方案


不确定如何在不检查更改值的情况下检查更改的属性。

带有反射的 LINQ 查询可用于查看哪些属性名称不再相同。这是紧凑的,不需要每个属性的 if 语句。

public record Animal 
{
    public string Name { get; init; }
    public string Type { get; init; }
    public string Genus { get; init; }
    public string Owner { get; init; }

    public Dictionary<string, string> ChangedProps(Animal animal)
    {
        return GetType()
            // Get all the names of object properties
            .GetProperties()

            // Convert to a List to use LINQ
            .Cast<PropertyInfo>()

            // Only get the properties whose values are not the same
            .Where(x => !GetType().GetProperty(x.Name).GetValue(this, null).Equals(GetType().GetProperty(x.Name).GetValue(animal, null)))

            // Create a KVP to add to a dictionary
            .Select(x => new KeyValuePair<string, string>( x.Name, (string)animal.GetType().GetProperty(x.Name).GetValue(animal, null) ))

            // Convert all the items that dont match into a dictionary
            .ToDictionary(x => x.Key, x => x.Value);
    }
}

这将返回一个包含更改的键和值的字典。


推荐阅读