我正在学习C#,并且正在学习将字段设为私有,并使用Getters和Setter来公开方法而不是字段值.
class Student { // Instance fields private string name; private int mark; // Method 1 public string Name { get; set; } // Method 2 public int Mark { get { return mark; } set { mark = value; } } }
最后,如果要在获取或设置值之前执行计算,是否使用方法2?例如将值转换为百分比或执行验证?例如
class Student { // Instance fields private string name; private double mark; private int maxMark = 50; // Method 1 public string Name { get; set; } // Method 2 public double Mark { get { return mark; } set { if ( mark <= maxMark ) mark = value / maxMark * 100; } } }