C# 'as'关键字是否会返回该类的所有成员?

C# 'as'关键字是否会返回该类的所有成员?,c#,interface,as-keyword,C#,Interface,As Keyword,我做了一些测试,发现了一些奇怪的东西。 假设我有这个接口 interface IRobot { int Fuel { get; } } 正如你所看到的,它是只读的。现在我要创建一个实现它的类 class FighterBot : IRobot { public int Fuel { get; set; } } 现在您可以阅读并设置它。让我们做一些测试: FighterBot fighterBot;

我做了一些测试,发现了一些奇怪的东西。 假设我有这个接口

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
这是意料之中的,然后我做了这个:

 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当作战士吗?因此,它是否能够设置燃油?

即使您通过“as”语句将
robot
投射到
FighterBot
,您仍将结果存储在
IRobot
类型的变量中,因此
燃油
仍然是只读的

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

var robot3 = robot as FighterBot;

然后它就会工作。

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

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.
您需要将转换结果存储在类型为
FighterBot
的变量中:

var robot3 = robot as FighterBot;
那就行了

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;
更多背景:

IRobot r = new FighterBot();
// you can only call method // properties that are described in IRobot
如果要与对象交互并设置属性,请使用为其设计的界面

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

IRobot的燃料确实是只读的,这是正确的!如果你说
var robot3=robot as FighterBot,它就会起作用。C#编译器使用声明的变量类型来确定可用的函数;给robot2分配一个新值不会改变原来声明的类型(仍然是IRobot)。IRobot的燃料确实是只读的,这是正确的!如果你说
var robot3=robot as FighterBot,它就会起作用。C#编译器使用声明的变量类型来确定可用的函数;为robot2分配新值不会更改原始声明的类型(仍然是IRobot)。