记录字段上是否有 C# 属性可以从比较中排除字段?

Mot*_*ohn 5 c# c#-9.0

我正在获取带有更新时间戳的数据,我想忽略该数据,例如:

public record Person
{
    public string LastName,
    public string FirstName,
    public string MiddleName,
    [isThereAnAttributeThatICanPutHere]
    public DateTime UpdatedAt
}
Run Code Online (Sandbox Code Playgroud)

C#record自动生成按值比较记录的代码,我想利用该功能,但需要排除一个字段。我知道我可以提供自己的,GetHashCode但这会违背试图保持简单的目的。我也知道我可以与以下内容进行比较:

person1 with {UpdateAt = null} == person2 with {UpdateAt = null}// 这需要 UpdatedAt 可以为空

但这看起来像是不必要的分配。

Gur*_*ron 1

不,目前没有内置任何内容,因此除非您愿意编写自己的自定义实现(可能使用源生成器),否则您只能手动覆盖Equals(和GetHashCodeJIC)。PrintMembers本期讨论了类似的内容 .NET 团队似乎没有考虑属性方法。