Possible to mix object initializer and collection initializer?(可以混合对象初始化器和集合初始化器吗?)
问题描述
我按照此处的说明使用 IEnumerable 定义了一个集合初始值设定项:http://msdn.microsoft.com/en-us/library/bb384062.aspx
现在我可以在我的集合初始化器中创建对象,并使用我的 Add() 方法添加它们,如下所示:
类 ArrangedPanel : RectElement{私有列表<RectElement>安排的孩子=新列表<矩形元素>();公共 int 填充 = 2;公共无效添加(矩形元素元素){安排儿童.添加(元素);//在这里做自定义的东西}公共 IEnumerator GetEnumerator(){返回排列的Children.GetEnumerator();}}//某处debugPanel.Add(新的 ArrangedPanel(){新的按钮切换(),新按钮切换()});
但是,如果我尝试设置一个属性,例如我的填充"字段,我会在集合初始值设定项上收到错误消息.
debugPanel.Add(new ArrangedPanel(){填充 = 5,新的按钮切换(),新按钮切换()});
是否可以同时设置集合初始化器和对象初始化器?
解决方案不幸的是,不能混合使用对象和集合初始化程序.C# 3.0 规范在第 7.5.10.1 节中将对象创建表达式定义为:
<上一页>对象创建表达式:new type (argument-listopt) object-or-collection-initializeroptnew type object-or-collection-initializer
如你所料,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:
class ArrangedPanel : RectElement
{
private List<RectElement> arrangedChildren = new List<RectElement>();
public int Padding = 2;
public void Add(RectElement element)
{
arrangedChildren.Add(element);
//do custom stuff here
}
public IEnumerator GetEnumerator()
{
return arrangedChildren.GetEnumerator();
}
}
// Somewhere
debugPanel.Add(new ArrangedPanel()
{
new ButtonToggle(),
new ButtonToggle()
});
However, if I try to set a property, such as my "Padding" field, I get an error on the collection initializers.
debugPanel.Add(new ArrangedPanel()
{
Padding = 5,
new ButtonToggle(),
new ButtonToggle()
});
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.
这篇关于可以混合对象初始化器和集合初始化器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以混合对象初始化器和集合初始化器吗?


- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01