C# Var 与 Target 类型的 new

Rab*_*820 7 c# var variable-declaration

C#9几天前正式发布。一项新的语言功能是“目标类型的新表达式”,它的使用感觉与var. 比较以下声明,我很好奇哪个性能更高(如果有的话),以及不同上下文应首选哪种语法。

var person = new Person()Person person = new()

对于收藏:

var people = new[] {
    new Person(),
    new Person(),
    new Person(),
}
Run Code Online (Sandbox Code Playgroud)

var people = new Person[] {
    new(),
    new(),
    new(),
}
Run Code Online (Sandbox Code Playgroud)

Gio*_*dze 7

var person = new Person()并将Person person = new()编译为相同的 IL 代码。它们只是告诉编译器要初始化哪种类型的两种不同方式;它们与运行时性能没有任何关系。

  • 目标类型 new 对于包含泛型的类级字段特别有用。就像 `private readonly Dictionary<string, SomeLongTypeName> _dict = new Dictionary<string, SomeLongTypeName>();` 与 `private readonly Dictionary<string, SomeLongTypeName> _dict = new();` (4认同)