问题描述
我正在学习 C#,并且正在学习如何将字段设为类私有,并使用 Getter 和 Setter 来公开方法而不是字段值.
I am learning C#, and am learning about making fields private to the class, and using Getters and Setters to expose Methods instead of field values.
是get;set;
在 Method 1 和 Method 2 等效?例如一个是另一个的简写吗?
Are the get; set;
in Method 1 and Method 2 equivalent? e.g. is one a shorthand of the other?
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?例如将值转换为百分比或执行验证?例如
Finally, would Method 2 be used when you want to for example perform a calculation before getting or setting a value? e.g. converting value to a percentage or perform validation? e.g.
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; }
}
}
推荐答案
是的,方法一是方法二的快捷方式,我建议默认使用方法一.当您需要更多功能时,请使用方法 2.您还可以为 get 和 set 指定不同的访问修饰符.
Yes, Method 1 is a shortcut to Method 2. I suggest using Method 1 by default. When you need more functionality, use Method 2. You can also specify different access modifiers for get and set.
这篇关于速记访问器和突变器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!