c# - c# 中 Get 和 Set 方法的目的是什么?

标签 c# methods get set

<分区>

我的大部分编程作业只是简单地创建与基类关联的子类。然而,随着我们的进步,对使用 get 和 set 方法的重视程度急剧增加。我只想有人向我解释这些是什么,以及如何以尽可能简单的方式使用它们。非常感谢!

最佳答案

C# 中的 Get 和 Set 方法是从 C++ 和 C 进化而来的,但后来被称为 properties 的语法糖所取代。

要点是您有一个变量或字段,您希望它的值是公开的,但您不希望其他用户能够更改它的值。

假设您有这段代码:

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 方式,称为 String Interpolation .

但是,由于此模式在 C/C++ 中经常使用,因此 C# 决定使用属性使其更容易,您绝对应该研究一下:)

关于c# - c# 中 Get 和 Set 方法的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423755/

相关文章:

c++ - 如何使用虚表正确调用成员方法?

algorithm - 运行时的渐近符号

java - Android 中的 HTTPURL 连接速度慢

javascript - 如何在另一个页面上使用Javascript的getElementById

c# - 如何创建 "custom protocol"并将其映射到应用程序?

c# - TFS2010 : How to link a WorkItem to a ChangeSet

pointers - bytes.Reader,替换底层 []byte 数组

c# - 如何通过Azure应用程序注册实现多资源授权?

c# - 什么是只读集合?

php - 通过 PHP 从 URL 获取 JSON