Shorthand Accessors and Mutators(速记访问器和突变器)
问题描述
我正在学习 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.
这篇关于速记访问器和突变器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:速记访问器和突变器


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01