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

私有变量经get/set封装后通过构造函数初始化仍无法访问的问题求助

问题原因及解决办法

原因

private修饰的成员变量仅能在类内部直接访问,和构造函数初始化逻辑无关。你遇到的报错,是因为在Main类里直接通过car.model、car.color访问私有字段——这完全违反了C#的访问权限规则,哪怕你已经定义了get/set方法,也不能跳过方法直接操作私有变量。

解决办法

必须通过你定义的get方法来获取私有变量的值,而非直接访问字段。以下是修正后的代码示例:

正确的Car类写法(以C#为例)

public class Car
{
    // 私有字段
    private string model;
    private string color;

    // 构造函数初始化字段
    public Car(string model, string color)
    {
        this.model = model;
        this.color = color;
    }

    // Get方法:对外提供私有字段的访问入口
    public string GetModel()
    {
        return model;
    }

    public string GetColor()
    {
        return color;
    }

    // Set方法:对外提供私有字段的修改入口(可选)
    public void SetModel(string newModel)
    {
        model = newModel;
    }

    public void SetColor(string newColor)
    {
        color = newColor;
    }
}

Main类中正确的调用方式

public class Program
{
    public static void Main()
    {
        Car myCar = new Car("Tesla Model 3", "Red");
        // 使用get方法获取值,而非直接访问私有字段
        Console.WriteLine($"Model: {myCar.GetModel()}");
        Console.WriteLine($"Color: {myCar.GetColor()}");
    }
}

额外优化:使用C#属性语法(更符合.NET规范)

如果是C#开发,更推荐用属性语法封装,编译器会自动生成对应的私有字段,写法更简洁:

public class Car
{
    // 自动属性:public访问级别,内部封装私有字段
    public string Model { get; set; }
    public string Color { get; set; }

    // 构造函数初始化属性
    public Car(string model, string color)
    {
        Model = model;
        Color = color;
    }
}

对应Main类的调用可以直接访问属性(属性是public级别,允许外部访问):

public static void Main()
{
    Car myCar = new Car("Tesla Model 3", "Red");
    Console.WriteLine($"Model: {myCar.Model}");
    Console.WriteLine($"Color: {myCar.Color}");
}

内容的提问来源于stack exchange,提问作者Hassan Abid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:20:23