C# init-only-setter


对象初始化器允许在对象初始化期间指定成员值。但是,任何只读属性都不能以这种方式设置,因为只有getter的属性只能在对象构造过程中设置,并且对象初始化器在此之后运行。为了解决这个问题,C#9.0添加了对init-only-setter的支持,它可以在对象初始化器中进行设置,但不能在之后进行设置。清单6.32演示了对Salary属性使用init-only-setter。

using System;
namespace HxRuntech
{
    public class T1
    {
        
        static void Main()
        {
            Employee employee = new(44, "huangxing")
            {
                Salary = "deff"
            };
            Console.WriteLine(employee.Salary);
        }
    }
    public class Employee
    {
        public Employee(int id, string name)
        {
            Id = id;
            Name = name;
            Salary = null;
        }
        public int Id { get;  }
        public string Name { get; }
        public string? Salary {
            get => _Salary;
            init => _Salary = value;
        }
        private string? _Salary;
    }
}