有两个类(分别是父子类):
class Unit
{
protected string UnitChar = ".";
public string Char
{
get => UnitChar;
}
public void Print() => Console.WriteLine(Char);
}
class Pawn : Unit
{
protected new string UnitChar = "P";
}
在继承的类中,我UnitChar用字符串覆盖该字段"P"。根据我的想法,继承的方法和属性Pawn,当从其实例调用时,应该使用其依赖于重写字段的字段和属性。换句话说,Print类中的继承方法Pawn必须使用 property Char,而 property 又返回重写的UnitChar.
然而,下面的代码:
Unit U = new();
Pawn P = new();
U.Print();
P.Print();
Console.WriteLine($"{U.Char} {P.Char}");
输出:
.
.
. .
虽然预计:
.
P
. P