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として扱っていませんか?したがって、Fuel を設定できるようにすべきではないでしょうか。

4

2 に答える 2

3

「as」ステートメントを介してキャストしている場合でもrobot、結果を型の変数に格納しているため、読み取り専用です。FighterBotIRobotFuel

変換の結果を次のタイプの変数に格納する必要があります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 に答える