对象初始化不适合我

时间:2012-09-27 21:13:54

标签: c# syntax object-initializers collection-initializer

我在这里缺少什么?我希望以下工作正常:

public class ProposalFileInfo
{
    public int FileId { get; set; }
    public bool IsSupportDocument { get; set; }
}

// ...

var attachments = new List<ProposalFileInfo>();

attachments.Add(new ProposalFileInfo { 1, false });
attachments.Add(new ProposalFileInfo { 2, false });
attachments.Add(new ProposalFileInfo { 3, false });

相反,我在最后三行中的{个字符处出现错误:

  

无法使用集合初始值设定项初始化类型'xxx.yyy.ProposalFileInfo',因为它没有实现'System.Collections.IEnumerable'

我没有使用Object initializer吗?为什么它假设一个集合初始化器? (我正在使用Visual Studio 2012。)

1 个答案:

答案 0 :(得分:8)

要使用对象初始化程序,您必须指定要设置的属性:

attachments.Add(new ProposalFileInfo { FileId = 1, IsSupportDocument = false });

因此,将整个初始化转换为集合初始值设定项,我们最终得到:

var attachments = new List<ProposalFileInfo>
{
    new ProposalFileInfo { FileId = 1, IsSupportDocument = false },
    new ProposalFileInfo { FileId = 2, IsSupportDocument = false },
    new ProposalFileInfo { FileId = 3, IsSupportDocument = false },
};

但是,只需向ProposalFileInfo添加构造函数即可使代码更简单:

public ProposalFileInfo(int fileId, bool isSupportDocument)
{
    FileId = fileId;
    IsSupportDocument = isSupportDocument;
}

然后您的初始化可以是:

var attachments = new List<ProposalFileInfo>
{
    new ProposalFileInfo(1, false),
    new ProposalFileInfo(2, false),
    new ProposalFileInfo(3, false)
};

如果您想要指定每个参数的含义(或其中一些),并且您使用C#4,则可以使用命名参数,例如

    new ProposalFileInfo(1, isSupportDocument: false),