在C#中获取和设置方法是从C++和C进化而来的,但后来被称为属性的合成糖取代
重点是您有一个变量或字段,您希望它的值是公共的,但您不希望其他用户能够更改其值.
想象一下你有这个代码:
public class Date
{
public int Day;
public int Month;
public int Year;
}
Run Code Online (Sandbox Code Playgroud)
现在,有人可以将Day设置为-42,显然这是一个无效的日期.那么,如果我们有什么东西阻止他们这样做呢?
现在我们创建set和get方法来规范进入和发生的事情,将代码转换为:
public class Date
{
// Private backing fields
private int day;
private int month;
private int year;
// Return the respective values of the backing fields
public int GetDay() => day;
public int GetMonth() => month;
public int GetYear() => year;
public void SetDay(int day)
{
if (day < 32 && day > 0) this.day = day;
}
public void SetMonth(int month)
{
if (month < 13 && month > 0) this.month = month;
}
public void SetYear(int year) => this.year = year;
}
Run Code Online (Sandbox Code Playgroud)
当然这是一个过于简单的例子,但它显示了如何使用它们.当然,您可以对getter方法进行计算,如下所示:
public class Person
{
private string firstName;
private string lastName;
public string GetFullName() => $"{firstName} {lastName}";
}
Run Code Online (Sandbox Code Playgroud)
这将返回名字和姓氏,以空格分隔.我写这个的方式是C#6方式,叫做String Interpolation.
但是,由于这种模式经常在C/C++中完成,因此C#决定使其更容易使用属性,你应该仔细研究:)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |