C#中Get & Set方法的目的是什么?
本文关键字:方法 是什么 Set Get amp | 更新日期: 2023-09-27 18:34:54
我的大部分编程作业只是简单地创建与基类相关的子类。然而,随着我们的进步,对使用get和set方法的重视程度急剧增加。我只是想有人向我解释这些是什么,以及如何以最简单的术语使用它们。非常感谢!
C# 中的 Get 和 Set 方法是从 C++ 和 C 演变而来的,但后来被一种称为属性的合成糖所取代。
重点是,您有一个变量或字段,您希望其值是公共的,但您不希望其他用户能够更改其值。
假设你有这样的代码:
public class Date
{
public int Day;
public int Month;
public int Year;
}
就目前而言,有人可以将 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;
}
当然,这是一个过于简单化的示例,但它显示了如何使用它们。当然,您可以对 getter 方法进行计算,如下所示:
public class Person
{
private string firstName;
private string lastName;
public string GetFullName() => $"{firstName} {lastName}";
}
这将返回名字和姓氏,用空格分隔。我写这个的方式是 C# 6 方式,称为字符串插值。
但是,由于此模式在 C/C++ 中经常执行,因此 C# 决定使用属性使其更容易,您绝对应该研究:)