考虑:
// 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) {
var r = new MyRec("hello");
Console.WriteLine(r.ToString());
}
}
{{链接1:sharplab}}
看起来基类 ToString
没有被继承,编译器仍然会自动生成派生的 Tostring
。
为什么会这样?有没有好的解决方法?