C#如何通过父类的对象访问嵌套类的方法?

时间:2015-05-23 00:03:42

标签: c# nested-class

public class City
{
  public class Population
  {
    public int number;
    public void change(int amount)
    {
      number = amount;
    }
  public class Buildings
  {...}
  public class Military
  {...}
}

让我们说在另一个班级,我有

public City[] PlayerCities = new City[6];

如果我尝试像PlayerCities[0].Population.Change(4)这样的内容,它就无法正常工作。

PS:我是初学者,我无法想到其他实现 - 这就是为什么我使用嵌套类 - 它似乎对我有意义

1 个答案:

答案 0 :(得分:0)

您需要先创建Population对象,然后才能访问其方法。另一种方法是将Change变为静态变量(在您的情况下没有意义,但重要的是要知道)。

在下面的代码中,我在Population

中创建了City的自动属性
public class City
{
  public Population Population {get; set;}
  public class Population
  {
    public int number;
    public void change(int amount)
    {
      number = amount;
    }
  public class Buildings
  {...}
  public class Military
  {...}
}

添加后,您可以执行PlayerCities[0].Population.Change(4)