.net init与get only属性的区别?[复制]

fzwojiic  于 2023-11-20  发布在  .NET
关注(0)|答案(2)|浏览(163)

此问题在此处已有答案

Property with private setter versus get-only-property(3个答案)
6天前关闭
C#中的init和get only属性有什么区别?
样品名称:

  1. public class person
  2. {
  3. public string Name { get; init; }
  4. public string Family { get; }
  5. }

字符串
我试图弄清楚,我理解他们两个都让你的财产只读,但我不知道有什么区别,当我们应该选择其中一个对另一个。

z2acfund

z2acfund1#

Get only属性只能在初始化对象时设置。Private set将允许您随时从该类中更改属性。

14ifxucb

14ifxucb2#

不同的是你可以在类中设置Name。而Family是只读的,所以只能在构造函数中设置。
例如

  1. var p = new Person("fam");
  2. p.SetName("name");
  3. public class Person
  4. {
  5. public Person(string family) // constructor
  6. {
  7. Family = family;
  8. }
  9. public void SetName(string name)
  10. {
  11. Name = name; // allowed from within
  12. }
  13. public void SetFamily(string family)
  14. {
  15. Family = family; // error
  16. }
  17. public string Name { get; private set; }
  18. public string Family { get; }
  19. }

字符串

展开查看全部

相关问题