-1

我有这样的事情:

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”不工作?

4

2 回答 2

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
于 2013-01-29T14:01:48.540 回答
3

您必须启动子类型(嵌套类型)的对象才能访问其方法,在您的情况下,您没有创建嵌套类型的任何对象,因此您无法访问其方法。

创建 anew Ship()时,您没有创建任何Engineor Piston,因此您无法访问Pistons()不存在对象的方法。

于 2013-01-29T14:08:09.343 回答