📜  C#7.0 表达体getter和setter

📅  最后修改于: 2020-11-01 03:09:26             🧑  作者: Mango

C#表达体getter和setter

C#表达式主体是单行表达式语句。它用于为方法,构造函数或属性提供单一生命周期定义。我们可以使用它来为getter和setter提供定义。

在下面的示例中,我们为getter和setter提供表达式主体。

C#Expression bodied getters and setters示例

using System;
namespace CSharpFeatures
{
    class Student
    {
        private string SName;
        public Student(string name) => SName = name;
        public string Name {
            get => SName;           // Expression body for getter
            set => SName = value;   // Expression body for setter
        }
    }
    class ExpressionExample
    {
        public static void Main()
        {
            Student student = new Student("Peter");
            Console.WriteLine(student.Name);
        }
    }
}

输出:

Peter