关键字"as"是否将该类的所有成员都带回来
本文关键字:quot 成员 回来 是否 as 关键字 | 更新日期: 2023-09-27 18:04:34
我一直在做一些测试,发现了一些奇怪的东西。假设我有这个接口
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吗?因此,它不应该设置燃料吗?
即使您通过"as"语句将robot
强制转换为FighterBot
,您也将结果存储在类型为IRobot
的变量中,因此Fuel
仍然是只读的。
您需要将转换结果存储在类型为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;