c# - 如何在记录类型中查找更改的属性名称和值?
问题描述
创建记录类型。
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));
如何在不比较每个属性值的情况下找到更改的值和属性名称?
解决方案
不确定如何在不检查更改值的情况下检查更改的属性。
带有反射的 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);
}
}
这将返回一个包含更改的键和值的字典。
推荐阅读
- c++ - 使用 malloc() 时出现意外大小
- image - 如何使用 OpenCV 查找图像上每个单独轮廓的高度和宽度
- rxjs - RxJs:您可以将运算符作为参数传播到管道运算符中吗
- html - 通过电子邮件发送 HTML 中的照片时出现问题
- javascript - fullcalendar timegridweek 不能正确显示事件时间
- video - 将 .mp4 批量转换为 hls 分段流
- driver - 如何从微型过滤器驱动程序中的 PUNICODESTRING 中提取 Volume 和 ParentDir?
- delphi - 较新的 Delphi 版本是否需要 FastStrings.pas?
- java - Heroku连接关闭而没有响应Java Spring-boot MySQL
- javascript - 静态文件使用 Angular 7 附加到表单数据中以发布 api http