来自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/