gpt4 book ai didi

c# - 如何使用 ReSharper 自动创建不可变属性?

转载 作者:太空狗 更新时间:2023-10-30 01:04:32 25 4
gpt4 key购买 nike

我发现自己按照以下模式创建了大量属性:

private readonly MyType sth;

public MyClass(MyType sth) //class constructor
{
this.sth = sth;
}

public MyType Sth
{
get { return sth; }
}

是否有一种简单的方法可以自动创建这些属性?通常我:

  1. 键入字段,包括只读关键字
  2. 选择“从构造函数参数初始化”
  3. 选择“封装”

有没有可能让它更快?

最佳答案

使用 C# 6,您的示例可以重写为:

private MyType sth { get; }

public MyClass(MyType sth) //class constructor
{
this.sth = sth;
}

这称为 getter-only 自动属性。当您删除“私有(private)集”时,属性后面的生成字段被声明为只读;像这样。

来自 https://msdn.microsoft.com/en-us/magazine/dn879355.aspx

Getter-only auto-properties are available in both structs and class declarations, but they’re especially important to structs because of the best practice guideline that structs be immutable. Rather than the six or so lines needed to declare a read-only property and initialize it prior to C# 6.0, now a single-line declaration and the assignment from within the constructor are all that’s needed. Thus, declaration of immutable structs is now not only the correct programming pattern for structs, but also the simpler pattern—a much appreciated change from prior syntax where coding correctly required more effort.

关于c# - 如何使用 ReSharper 自动创建不可变属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22940700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com