我一直在做一些测试,发现了一些奇怪的东西。 说我有这个接口`as`关键字是否带回班级的所有成员?
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
它为什么不工作?它不是把机器人2当成FighterBot吗?因此,它不应该能够设置燃料?
IRobot's Fuel的确是只读的,这是正确的! – David 2013-03-17 13:34:23
如果你说'var robot3 = robot作为FighterBot;'它会起作用。 C#编译器使用声明的变量类型来确定哪些函数可用;给robot2分配一个新的值不会改变原来的声明类型(它仍然是IRobot)。 – 2013-03-17 13:34:27