c#getters setters风格

use*_*265 2 c# getter setter properties private

我正在研究一些代码,其中有很多这样的代码:

private int x;

public void SetX(int new_x)
{
   this.SetXValue(new_x); 
}

private void SetXValue(int new_x)
{
   this.x = new_x; 
}
Run Code Online (Sandbox Code Playgroud)

和类似的属性:

private int x;

public int X 
{
    get { return this.GetX(); }
}

private int GetX()
{
    return this.x; 
}
Run Code Online (Sandbox Code Playgroud)

我没有得到的是为什么需要私有方法来做实际工作,即为什么不只是有这样的方法:

public void SetX(int new_x) 
{
  this.x = new_x;
}

public int X
{
    get { return this.x; }
}
Run Code Online (Sandbox Code Playgroud)

它只是其他人的个人选择还是有一些使用第一种方式的充分理由?

(我手动输入上面的代码很抱歉,如果有任何错误,但你应该希望看到我想说的话)

干杯A.

Lex*_*ust 7

就我所见,没有理由像这样的代码.如果你没有对新值做任何事情(比如在存储之前处理/检查)并且你正在编写C#3.0,你实际上可以将它简写为:

public int MyProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)

编译器为您创建后备存储,您只需引用:

this.MyProperty
Run Code Online (Sandbox Code Playgroud)

......在你的班级里面.您还可以创建仅限get的属性,例如:

public int MyProperty { get; private set; }
Run Code Online (Sandbox Code Playgroud)

我认为所有这些都非常整洁!