C# 速记访问器和修改器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16752577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shorthand Accessors and Mutators
提问by Gravy
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.
我正在学习 C#,并且正在学习如何将字段设为类私有,并使用 Getter 和 Setter 来公开方法而不是字段值。
Are the get; set;in Method 1and Method 2equivalent? e.g. is one a shorthand of the other?
是get; set;在方法1和方法2相同呢?例如,一个是另一个的简写吗?
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; }
}
}
Finally, would Method 2be 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.
最后,当您想在获取或设置值之前执行计算时,是否会使用方法 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; }
}
}
采纳答案by Robin
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.
是的,方法一是方法二的快捷方式。我建议默认使用方法一。当您需要更多功能时,请使用方法 2。您还可以为 get 和 set 指定不同的访问修饰符。
回答by Saravanan
Yes, the Method2is the way to go when you have a custom getter and setter function. By default when you use Method1, there will be a default private property handled internally. Please refer this URLfor more details.
是的,Method2当你有一个自定义的 getter 和 setter 函数时,这是要走的路。默认情况下,当您使用 Method1 时,将有一个内部处理的默认私有属性。有关详细信息,请参阅此URL。
Sample:
样本:
string _name;
public string Name
{
get => _name;
set => _name = value;
}

