c# - 使用 new(...) 时哪些情况是无争议的?

标签 c# visual-studio-2019

来自release notes对于 Visual Studio 2019 版本 16.9:

There is now a refactoring that suggests using new(…) in non-contentious scenarios.

什么是无争议场景和有争议场景?

最佳答案

归功于Jeroen Mostert用于查找原始功能请求

Add new feature to suggest using 'new(...)' in non-contentious scenarios

Only appears in scenarios where the type is obvious from syntax. i.e. field declarations. Will not appear in cases where the existing 'var' preference would prefer that be 'var' instead.

基本上,该功能是说,当 var 在上下文中不是首选时,它会给您建议。

有争议的例子

List<string> bob = new List<String>();

在上述情况下,它会更倾向于建议 var

var bob = new List<String>(); 

无争议示例

public class Bob
{
    List<string> _bob = new List<String>();
}

在上面的情况下,无法使用var,因此会建议new()。这是因为上下文关键字 var 只能出现在局部变量声明中。

public class Bob
{
    List<string> _bob = new();
}

另一个无争议的示例

var derp = new List<Bob>()
   {
      new Bob(),
      new Bob(),
      new Bob(),
   }

上面是建议 new()

的有效位置
var derp = new List<Bob>()
   {
      new(),
      new(),
      new(),
   }

请注意 Jeroen Mostert,如果您回答,我将删除此帖子。

关于c# - 使用 new(...) 时哪些情况是无争议的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66471630/

相关文章:

Nuget 包管理器已损坏 - '' 不是 VS2019 中的有效版本字符串 "Manage Packages for Solution"

C# - 使用 RGB 值在颜色对话框中设置自定义颜色

c# - Azure 存储 - 403 禁止访问

c++ - 更改 volatile const 的值 - G++ 与 Visual Studio 2019

c# - 如何在不编辑文件的情况下仅在生成的代码中禁用编译器警告

windows - 浏览器中的 jupyter notebook 黑屏

c# - async 和 await 不起作用

c# - 如何在 WCF 服务 wsdl 链接中用域名替换机器名

c# - 在 ASP.NET 中使用 C# 全局变量的正确方法?

sql-server - 如何从 ASP.NET Core Entity Framework 中的数据库更新 VS 2019 中的模型