我一直在做一些測試,發現了一些奇怪的東西。 說我有這個接口`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