简体   繁体   English

C#对象初始化

[英]C# object initialization

Having program with such code : 有这样的代码的程序:

var subtree = new Tree<int>(5, EnumeratorOrder.BreadthFirstSearch) { 1, 2 };

var tree = new Tree<int>(7, EnumeratorOrder.BreadthFirstSearch) { subtree, 10, 15 };

I сan't understan what means { 1, 2 } ? 我不明白{ 1, 2 }是什么意思?

I сan't understan what means { 1, 2 } 我不明白{1,2}是什么意思

The {1, 2} are Collection Initializers . {1, 2}集合初始化器

They represent a short-hand version of 它们代表了

var temp = new Tree<int>(5, EnumeratorOrder.BreadthFirstSearch);
temp.Add(1);
temp.Add(2);

var subtree = temp;

Note regarding initial assignment to temp : The meaning of assignment is evaluate the left, evaluate the right, do the assignment. 有关对temp进行初始分配的注意事项:分配的含义是评估左侧,评估右侧,进行分配。 Evaluating the right produces side effects, and those effects must be ordered before the effect of the assignment. 评估权利会产生副作用,必须在分配效果之前对这些效果进行排序。 See comments for a full discussion. 请参阅评论以进行完整讨论。

It's a collection initializer . 这是一个集合初始化器

Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable or a class with an Add extension method. 集合初始化器可让您在初始化实现IEnumerable的集合类或带有Add扩展方法的类时指定一个或多个元素初始化器。 The element initializers can be a simple value, an expression or an object initializer. 元素初始值设定项可以是简单值,表达式或对象初始值设定项。 By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; 通过使用集合初始值设定项,您不必在源代码中指定对类的Add方法的多次调用;而是,可以使用默认值。 the compiler adds the calls. 编译器将添加调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM