C# encapsulation (get and set)



我在Head First C#书中做练习。

这段代码应该是关于封装的。

class DinnerParty
{
    private int NumberOfPeople;
         ....
    public void SetPartyOptions(int people, bool fancy) {
        NumberOfPeople = people;
        .....
    }
    public int GetNumberOfPeople() {
        return NumberOfPeople;
    }
}

form1类中

public partial class Form1 : Form
{
    DinnerParty dinnerParty;
    public Form1()
    {
        InitializeComponent();
        dinnerParty = new DinnerParty() {NumberOfPeople = 5 };
        ...

这样行得通吗?

Visual Studio显示了一个错误。(由于其保护级别而无法访问)

我对此很陌生。

感谢

这是因为NumberOfPeopleprivate意味着它不能从类DinnerParty之外访问,所以你需要使它成为public

不,这不应该起作用。我看不到这本书,所以我不能评论上下文。但是:

public int NumberOfPeopoe {get;set;} 

是一个合理的解决方案。

您可以通过编写以下内容来使用"Fluent接口"的概念:

class DinnerParty
{
    private int NumberOfPeople;
         ....
    public DinnerParty SetPartyOptions(int people, bool fancy) {
        NumberOfPeople = people;
        .....
        return this; // Return own instance to allow for further accessing.
    }
    public int GetNumberOfPeople() {
        return NumberOfPeople;
    }
}

然后称之为:

public partial class Form1 : Form
{
    DinnerParty dinnerParty;
    public Form1()
    {
        InitializeComponent();
        dinnerParty = new DinnerParty().SetPartyOptions( 5, true );
        ...

NumberOfPeople是一个私人成员,您不能在类外使用它dude

NumberOfPeople是私有的,因此它不起作用。这里最好的解决方案是创建公共属性而不是私有字段,或者添加构造函数并在那里初始化此字段。

您不能初始化范围(类)之外的私有字段。

让它成为一处房产。

public int NumberOfPeople { get; set; }

现在,这将工作

dinnerParty = new DinnerParty() { NumberOfPeople = 5 };

最新更新