我看到很多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的价值.但是,如果你只是传递价值观,那似乎是不必要的冗长.