2013-03-17 65 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;