我一直在做一些测试,遇到了一些奇怪的事情。说我有这个界面
interface IRobot
{
int Fuel { get; }
}
如您所见,它是只读的。所以现在我要创建一个实现它的类
class FighterBot : IRobot
{
public int Fuel { get; set; }
}
现在您可以阅读并设置它。所以让我们做一些测试:
FighterBot fighterBot;
IRobot robot;
IRobot robot2;
int Fuel;
public Form1()
{
InitializeComponent();
fighterBot = new FighterBot();
robot = new FighterBot();
}
首先我这样做:
Fuel = fighterBot.Fuel;// Can get it
fighterBot.Fuel = 10; //Can set it
这是意料之中的,然后我这样做了:
Fuel = robot.Fuel; //Can get it
robot.Fuel = 10; //Doesn't work, is read only
也值得期待。但是当我这样做时:
robot2 = robot as FighterBot;
Fuel = robot2.Fuel; //Can get it
robot2.Fuel = 10;//Doesn't work, is read only
为什么它不起作用?不是把robot2当成FighterBot吗?因此,它不应该能够设置燃料吗?