使用单个元素定义和设置数组属性

时间:2016-01-16 15:51:25

标签: c# arrays

我有一个类如下,它是一个API,所以它必须是这种格式

public class Command
{
    public string response_type { get; set; }
    public string text { get; set; }
    public Attachment[] attachments { get; set; } = new Attachment[] { new Attachment { } };
}

public class Attachment
{
    public string title { get; set; }
    public string title_link { get; set; }
    public string image_url { get; set; }
}

所以它是一个response_type,text和附件数组。您可以看到我创建了附件数组并创建了一个空对象。

创建对象时,数组中只会有一个元素。

如果已经在构造函数中创建了对象,我如何在声明对象时设置或添加数组

Command result = new Command()
{
    text = "Rebooting!",
    attachments[0] = ????
};

我遗漏了一些简单的东西,尝试了很多组合

2 个答案:

答案 0 :(得分:3)

您可以使用数组初始值设定项,只需使用一个项目:

Command result = new Command()
{
    text = "Rebooting!",
    attachments = new [] {new Attachment {...} }
};

作为旁注,大多数.NET命名标准都以大写字母(Attachments

开始属性名称

答案 1 :(得分:3)

要添加到数组,您需要在构造之后执行

Command result = new Command()
{
    text = "Rebooting!",
};

result.attachments = new Attachment[2] { result.attachments[0], new Attachment() };

如果您只想设置值(因为数组已经创建并包含一个实例,您可以

result.attachments[0] = new Attachment();