You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何访问父对象的属性?以城市类访问所属国家属性为例

解决City类访问所属Country属性的问题

当前代码报错的核心原因是City类和Country类之间未建立关联关系,City无法直接访问Country的NameOfCountry属性。要实现需求,需给City添加指向所属Country的引用,并在实例化City时传入对应Country对象。

修改后的完整代码

public class Country
{
    public string NameOfCountry { get; set; }
    public List<City> Cities { get; set; }

    public Country()
    {
        NameOfCountry = "USA";
        // 初始化城市列表
        Cities = new List<City>();
        // 创建城市时传入当前国家实例(this),建立关联
        Cities.Add(new City(this));
    }
}

public class City
{
    // 添加属性存储所属国家的引用
    public Country BelongsToCountry { get; set; }

    // 构造函数接收Country参数,完成关联赋值
    public City(Country country)
    {
        BelongsToCountry = country;
        Console.WriteLine("Hello. I live in " + BelongsToCountry.NameOfCountry);
    }
}

关键修改说明

  • 给City类新增BelongsToCountry属性,用于保存所属的Country对象引用。
  • 修改City的构造函数,接收Country类型参数,将传入的国家对象赋值给BelongsToCountry。
  • 在Country的构造函数中初始化Cities列表,并创建City实例时传入当前Country对象(this),确保城市与国家的关联关系。

调用示例

// 实例化国家时会自动创建关联的城市,控制台将输出"Hello. I live in USA"
var usa = new Country();

内容的提问来源于stack exchange,提问作者Ebrahim Mehri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 02:57:28