我有这样的事情:
public class Ship
{
public void PositionX_pixels_set1(float _position_x){position_x = _position_x;}
public class Engine : Ship
{
public int engines() { return 5; }
public class Piston
{
public int pistons(){return 5;}
}
}
}
void Main
{
Ship ship = new Ship()
int a = ship.Engine.Piston.pistons;//why this not working?
}
我不知道我做错了什么。为什么“ship.Engine.Piston.pistons”不工作?
答案 0 :(得分:5)
因为Engine
类中的Ship
类型及其成员。
要解决此问题,可以执行以下操作:
public class Ship
{
public void PositionX_pixels_set1(float _position_x){position_x = _position_x;}
private void Engine _myEngine = new Engine(); //DEFINE ENGINE MEMBER
public Engine MyEngine { //DEFINE A PROPERTY TO ACCESS THAT MEMBER
get {
return _myEngine;
}
}
public class Engine : Ship
{
public int engines() { return 5; }
private Piston _myPiston = new Piston();//DEFINE PISTON MEMBER
public Piston MyPiston {//DEFINE A PROPERTY TO ACCESS THAT
get {
return _myPiston ;
}
}
public class Piston
{
public int pistons(){return 5;}
}
MEMBER
}
}
使用后就像:
int a = ship.MyEngine.MyPiston.pistons
答案 1 :(得分:3)
您必须启动子类型的对象(嵌套类型)才能访问其方法,如果您没有创建嵌套类型的任何对象,则无法访问其方法。
在您创建new Ship()
时,您没有创建任何Engine
或Piston
,因此您无法访问非现有对象的方法Pistons()
。