Possible to mix object initializer and collection initializer?(可以混合对象初始化器和集合初始化器吗?)
问题描述
我按照此处的说明使用 IEnumerable 定义了一个集合初始值设定项:http://msdn.microsoft.com/en-us/library/bb384062.aspx
现在我可以在我的集合初始化器中创建对象,并使用我的 Add() 方法添加它们,如下所示:
如你所料,object-or-collection-initializer
要么是一个对象初始化器,要么是 一个集合初始化器.没有可用于将 then 组合在一起的语法.
I define an collection initializer with IEnumerable as instructed here: http://msdn.microsoft.com/en-us/library/bb384062.aspx
Now I'm able to create objects within my collection initializer and they are added wih my Add() method like so:
However, if I try to set a property, such as my "Padding" field, I get an error on the collection initializers.
Is it possible to set both collection initializers and object initializers?
Unfortunately it is not possible to mix object and collection initializers. The C# 3.0 specification defines an object creation expression in section 7.5.10.1 as:
object-creation-expression: new type ( argument-listopt ) object-or-collection-initializeropt new type object-or-collection-initializer
As you might expect, object-or-collection-initializer
is either an object initializer or a collection initializer. There is no syntax available for combining then together.
这篇关于可以混合对象初始化器和集合初始化器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!