man*_*ore 12 c# syntactic-sugar new-operator
C# 中没有类型有什么新功能?
我在工作中遇到如下代码:
throw new("some string goes here");
这是new("some string goes here")在 C# 中创建字符串的方法还是其他方法?
SO *_*ood 14
在具体情况下throw,throw new()是 的简写throw new Exception()。该功能是在 c# 9 中引入的,您可以在Target-typed new statements中找到文档。
正如您所看到的,有很多地方可以使用它(只要可以推断要创建的类型)来缩短代码。
我最喜欢它的地方是字段/属性:
private readonly Dictionary<SomeVeryLongName, List<AnotherTooLongName>> _data = new();
Run Code Online (Sandbox Code Playgroud)
作为补充说明,不鼓励使用throwing Exception,因为它对于大多数情况来说不够具体,所以我真的不建议这样做throw new ("error");。有很多特定的异常可供使用,如果这些都不起作用,请考虑创建自定义异常。
Phi*_*gan 10
创建一个可以从上下文推断new()类型的对象。
所以而不是:
throw new System.Exception("hi");
Run Code Online (Sandbox Code Playgroud)
您可以使用以下缩写形式:
throw new ("hi");
Run Code Online (Sandbox Code Playgroud)
相似地,
var s = new string("hello");
Run Code Online (Sandbox Code Playgroud)
可以替换为:
string s = new("hello");
Run Code Online (Sandbox Code Playgroud)