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.
这篇关于可以混合对象初始化器和集合初始化器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以混合对象初始化器和集合初始化器吗?
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01