相关疑难解决方法(0)

我应该在 C# 12 中为主构造函数参数创建私有属性吗?

我正在使用 C# 12。在 C# 12 中我可以使用主构造函数:

实施1:

public class Calculation(int a,int b)
{
  public int Addition() => a + b;
  public int Subtraction() => a - b;
}
Run Code Online (Sandbox Code Playgroud)

实施2:

public class Calculation(int a,int b)
{
 private int _a { get; init; } = a;
 private int _b { get; init; } = b;
 public int Addition() => _a + _b;
 public int Subtraction() => _a - _b;
}
Run Code Online (Sandbox Code Playgroud)

当我像这样调用这个方法时:

console.WriteLine(new Calculation(10,25).Addition());
Run Code Online (Sandbox Code Playgroud)

两种实现都工作正常,所以我想知道使用较长的实现 2 相对于较短的实现 1 是否有任何优势。

c# primary-constructor .net-8.0 c#-12.0

10
推荐指数
2
解决办法
1548
查看次数

标签 统计

.net-8.0 ×1

c# ×1

c#-12.0 ×1

primary-constructor ×1