【问题标题】:What is the purpose of Get & Set methods in c#? [duplicate]c#中Get和Set方法的目的是什么? [复制]
【发布时间】:2016-02-16 04:27:54
【问题描述】:

我的大部分编程任务只是简单地创建与基类相关的子类。然而,随着我们的进步,对使用 get & set 方法的强调会急剧增加。我只想有人向我解释这些是什么,以及如何以最简单的方式使用它们。非常感谢!

【问题讨论】:

  • 您不需要 c# 中的 get/set 方法。你有 Properties 以更优雅的方式模仿它。
  • 虽然我感觉这个问题会被关闭,但我想知道您所说的“获取和设置方法”是否实际上是获取和设置属性?我不记得曾经在 C# 中使用过实际的 get 或 set 方法...

标签: c# methods get set


【解决方案1】:

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# 决定使用属性使其更容易,您绝对应该研究一下 :)

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 2011-04-14
    • 2014-12-11
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    相关资源
    最近更新 更多