[英]Method overriding in an inherited record
Is it expected behavior with records in C#10? C#10 中的记录是预期的行为吗?
Console.WriteLine(new Derived1()); // =output=> Derived1 { }
Console.WriteLine(new Derived2()); // =output=> Base
record Base
{
public override string ToString() => "Base";
}
record Derived1 : Base;
record Derived2 : Base
{
public override string ToString() => base.ToString();
}
Yes, it is.是的。 Compiler will automatically generate formatting for display by overriding ToString
for every record:编译器将通过为每条记录覆盖ToString
来自动生成显示格式:
Record types have a compiler-generated
ToString
method that displays the names and values of public properties and fields.记录类型具有编译器生成的ToString
方法,该方法显示公共属性和字段的名称和值。 TheToString
method returns a string of the following format:ToString
方法返回以下格式的字符串:
<record type name> { <property name> = <value>, <property name> = <value>, ...}
unless you override it yourself (as you do in Derived2
and Base
).除非您自己覆盖它(就像您在Derived2
和Base
中所做的那样)。
See the sharplab.io decompilation.参见Sharplab.io反编译。
Also note next:接下来还要注意:
In C# 10 and later, your implementation of
ToString
may include thesealed
modifier, which prevents the compiler from synthesizing a ToString implementation for any derived records.在 C# 10 及更高版本中,您的ToString
实现可能包含sealed
修饰符,这会阻止编译器为任何派生记录合成 ToString 实现。
So if your base implementation is sufficient you can just seal it to prevent compiler from generating overrides:因此,如果您的基本实现足够,您可以将其密封以防止编译器生成覆盖:
record Base
{
public sealed override string ToString() => "Base";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.