我正在编写一些代码,其中有很多这样的代码:
private int x;
public void SetX(int new_x)
{
this.SetXValue(new_x);
}
private void SetXValue(int new_x)
{
this.x = new_x;
}
与属性类似:
private int x;
public int X
{
get { return this.GetX(); }
}
private int GetX()
{
return this.x;
}
我不明白的是为什么需要私有(private)方法来完成实际工作,即为什么不使用这样的方法:
public void SetX(int new_x)
{
this.x = new_x;
}
public int X
{
get { return this.x; }
}
这只是其他人的个人选择还是有充分的理由使用第一种方式?
(我手动输入了上面的代码,如果有任何错误,我深表歉意,但希望您能看到我想说的)
干杯 一个
最佳答案
据我所知,没有理由使用这样的代码。如果您没有对新值执行任何操作(例如存储前的处理/检查)并且您正在编写 C# 3.0,您实际上可以将其简写为:
public int MyProperty { get; set; }
编译器会为您创建后备存储,您可以直接引用:
this.MyProperty
...在你的类(class)里。您还可以创建 get-only 属性,例如:
public int MyProperty { get; private set; }
我认为所有这些都非常简洁!
关于C# getters setters 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9735670/