init关键字:
1.init在属性或索引器中定义访问器方法
2.仅在对象构造期间为属性或索引器元素赋值
3.init强制实施不可变性(对象一旦初始化,将无法更改)
4.如下同时定义get和init访问器
class Person_InitExample { private int _yearOfBirth; public int YearOfBirth { get { return _yearOfBirth; } init { _yearOfBirth = value; } } }
var john = new Person_InitExample { YearOfBirth = 1984 }; john.YearOfBirth = 1926; //不起作用,init关键字只允许在初始化对象过程中指定值
5.init访问器不强制调用方法设置属性(允许调用方使用对象初始化设定项,同时禁止以后的修改)
class Person_InitExampleNullability { private int? _yearOfBirth; //定义一个以可为空的值类型作为支持字段的仅init属性 public int? YearOfBirth { get => _yearOfBirth; init => _yearOfBirth = value; } }
6.若要强制调用方设置初始化非null值,添加required修饰符
//强制调用方设置初始非 null 值,可添加 required 修饰符 class Person_InitExampleNonNull { private int _yearOfBirth; public required int YearOfBirth { get => _yearOfBirth; init => _yearOfBirth = value; } }
7.init访问器用作表达式主题成员
class Person_InitExampleExpressionBodied { private int _yearOfBirth; public int YearOfBirth { get => _yearOfBirth; init => _yearOfBirth = value; } }
8.init访问器在自动实现的属性中使用
class Person_InitExampleAutoProperty { public int YearOfBirth { get; init; } }
9.private set属性 只读 属性和init属性区别
private set 版本和 read only 版本都需要调用方使用添加的构造函数来设置 name 属性。 通过 private set
版本,人员可在构造实例后更改其名称。 init
版本不需要构造函数。 调用方可使用对象初始值设定项初始化属性:
class PersonPrivateSet { public string FirstName { get; private set; } public string LastName { get; private set; } public PersonPrivateSet(string first, string last) => (FirstName, LastName) = (first, last); public void ChangeName(string first, string last) => (FirstName, LastName) = (first, last); } class PersonReadOnly { public string FirstName { get; } public string LastName { get; } public PersonReadOnly(string first, string last) => (FirstName, LastName) = (first, last); } class PersonInit { public string FirstName { get; init; } public string LastName { get; init; } } PersonPrivateSet personPrivateSet = new("Bill", "Gates"); PersonReadOnly personReadOnly = new("Bill", "Gates"); PersonInit personInit = new() { FirstName = "Bill", LastName = "Gates" };
标签:string,get,C#,yearOfBirth,private,init,public,属性 From: https://www.cnblogs.com/echo-efun/p/18420895