簡體   English   中英

C#如何訪問父類的嵌套類槽對象的方法?

[英]C# How do I access method of nested class trough object of parent 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:我是一個初學者,我想不出其他實現-這就是為什么我使用嵌套類-對我來說似乎很有意義

您需要先創建Population對象,然后才能訪問其方法。 這樣做的另一種方法是使Change為靜態變量(在您的情況下這沒有意義,但重要的是要知道)。

在下面的代碼中,我創建了City內部Population的汽車屬性

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM