使用 new(...) 时什么是无争议的场景?
What are non-contentious scenarios when using new(...)?
来自 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 请注意,如果您回答,我将删除此 post。
来自 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 请注意,如果您回答,我将删除此 post。