使用getter和setter的优点是什么 - 只能获取和设置 - 而不是简单地使用公共字段来存储这些变量?
如果getter和setter做的不仅仅是简单的get/set,我可以非常快地解决这个问题,但我并不是100%清楚如何:
public String foo;
Run Code Online (Sandbox Code Playgroud)
更糟糕的是:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Run Code Online (Sandbox Code Playgroud)
而前者需要很少的样板代码.
我看到很多C#类的示例代码执行此操作:
public class Point {
public int x { get; set; }
public int y { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
或者,在旧代码中,具有显式私有支持值并且没有新的自动实现属性:
public class Point {
private int _x;
private int _y;
public int x {
get { return _x; }
set { _x = value; }
}
public int y {
get { return _y; }
set { _y = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么.在执行上述操作与仅将这些成员设为公共字段之间是否有任何功能差异,如下所示?
public class Point {
public int x;
public int y;
}
Run Code Online (Sandbox Code Playgroud)
为了清楚起见,当您需要对基础数据进行一些翻译时,我理解了getter和setter的价值.但是,如果你只是传递价值观,那似乎是不必要的冗长.