2013-03-17 30 views
2

我一直在做一些测试,发现了一些奇怪的东西。 说我有这个接口`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吗?因此,它不应该能够设置燃料?

+1

IRobot's Fuel的确是只读的,这是正确的! – David 2013-03-17 13:34:23

+0

如果你说'var robot3 = robot作为FighterBot;'它会起作用。 C#编译器使用声明的变量类型来确定哪些函数可用;给robot2分配一个新的值不会改变原来的声明类型(它仍然是IRobot)。 – 2013-03-17 13:34:27

回答

3

即使你在这样Fuel还是只读IRobot类型的变量通过“作为”语句,你把结果存储铸造robotFighterBot

你需要转换的结果存储在FighterBot类型的变量:

var robot3 = robot as FighterBot; 

然后它会奏效。

+0

噢好吧,我现在明白了。非常感谢! – CsharpFrustration 2013-03-17 13:39:59

1
interface IRobot 
{ 
    int Fuel { get; } 
} 

robot2 = robot as FighterBot; 
Fuel = robot2.Fuel; 

// robot2 is STILL stored as IRobot, so the interface allowed 
// to communicate with this object will be restricted by 
// IRobot, no matter what object you put in (as long as it implements IRobot) 
robot2.Fuel = 10; // evidently, won't compile. 

一些更多的上下文:

IRobot r = new FighterBot(); 
// you can only call method // properties that are described in IRobot 

如果你想与该对象并设置属性交互,使用设计的界面吧。

FigherBot r = new FighterBot(); 
r.Fuel = 10;