我一直在做一些测试并遇到了一些奇怪的事情。 说我有这个界面
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?因此,它不应该能够设置燃料吗?
答案 0 :(得分:3)
即使您通过“as”语句将robot
强制转换为FighterBot
,您也会将结果存储在IRobot
类型的变量中,因此仍会读取Fuel
仅
您需要将转化结果存储在FighterBot
类型的变量中:
var robot3 = robot as FighterBot;
然后它会起作用。
答案 1 :(得分: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;