我真的很喜欢 C# 9 记录。但是,我找不到一种优雅而简洁的方法来完成这样的事情:
record MyKey(string Foo, int Bar);
[Fact]
public void ShouldEqualIgnoreCase()
{
MyKey a = new("ID", 42);
MyKey b = new("Id", 42);
Assert.Equal(a, b);
}
Run Code Online (Sandbox Code Playgroud) 我正在获取带有更新时间戳的数据,我想忽略该数据,例如:
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 可以为空
但这看起来像是不必要的分配。
考虑:
// the ratioale for Wrapper is that it has a Json serializer that
// serialize through Field (not included in this example)
record Wrapper<T> where T : notnull {
protected Wrapper(T field) => Field = field;
protected Wrapper(Wrapper<T> wrapper) => Field = wrapper.Field;
protected readonly T Field;
public override string ToString() => Field.ToString() ?? "";
}
record MyRec : Wrapper<string> {
public MyRec(string s) : base(s) {}
}
public static class Program {
public static void Main(string[] args) { …Run Code Online (Sandbox Code Playgroud)