可以混合对象初始化器和集合初始化器吗? [英] Possible to mix object initializer and collection initializer?

查看:53
本文介绍了可以混合对象初始化器和集合初始化器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照此处的说明使用 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.

这篇关于可以混合对象初始化器和集合初始化器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆