2

我一直在做一些测试,遇到了一些奇怪的事情。说我有这个界面

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吗?因此,它不应该能够设置燃料吗?

4

2 回答 2

3

即使您通过“as”语句进行转换robotFighterBot您也将结果存储在类型变量中,IRobot因此Fuel仍然是只读的。

您需要将转换结果存储在类型变量中FighterBot

var robot3 = robot as FighterBot;

然后它将起作用。

于 2013-03-17T13:36:39.850 回答
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;
于 2013-03-17T13:40:17.523 回答