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

无法向已创建类内部的List添加值?技术咨询

问题原因及解决方案

你的问题核心是类中List集合的访问权限不足。在C#中,类的成员默认是private访问级别,外部代码无法直接访问这些私有集合,所以调用Add方法会失败(甚至编译阶段就会报错)。

下面是三种可行的解决方式:

1. 直接修改集合的访问修饰符为public

将List的访问级别改为public,让外部代码可以直接操作集合:

class Vehicles
{
    public List<string> carType_list = new List<string>();
    public List<string> carModel_list = new List<string>();
    public List<int> seatCapacity_list = new List<int>();
    public List<string> mileageLimit_list = new List<string>();
    public List<double> ratings_list = new List<double>();
    public List<double> rentPrice_list = new List<double>();
}

使用示例:

Vehicles myVehicles = new Vehicles();
myVehicles.carType_list.Add("SUV");

2. 封装为公共属性(推荐,符合面向对象封装原则)

用属性封装集合,同时保持字段私有,既允许外部访问集合,又能在需要时添加逻辑:

class Vehicles
{
    public List<string> CarTypeList { get; set; } = new List<string>();
    public List<string> CarModelList { get; set; } = new List<string>();
    public List<int> SeatCapacityList { get; set; } = new List<int>();
    public List<string> MileageLimitList { get; set; } = new List<string>();
    public List<double> RatingsList { get; set; } = new List<double>();
    public List<double> RentPriceList { get; set; } = new List<double>();
}

使用示例:

Vehicles myVehicles = new Vehicles();
myVehicles.CarTypeList.Add("Sedan");

注:这里采用了C#的命名规范——属性名使用PascalCase(首字母大写),比下划线命名更符合行业惯例。

3. 提供专用的添加方法(完全封装内部逻辑)

如果不想暴露整个集合,可编写专门的添加方法,完全控制集合的访问逻辑(比如添加前做参数验证):

class Vehicles
{
    private List<string> carType_list = new List<string>();
    // 其他私有集合定义...

    public void AddCarType(string carType)
    {
        if (!string.IsNullOrEmpty(carType)) // 添加参数验证
        {
            carType_list.Add(carType);
        }
    }

    // 对应其他集合的添加方法,比如AddCarModel、AddSeatCapacity等
}

使用示例:

Vehicles myVehicles = new Vehicles();
myVehicles.AddCarType("Truck");

内容的提问来源于stack exchange,提问作者Anthony Felix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:25:38