【问题标题】:Define and set an array property with a single element [duplicate]使用单个元素定义和设置数组属性[重复]
【发布时间】:2016-04-22 02:25:30
【问题描述】:

我有一个类如下,它是一个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、文本和附件数组。你可以看到我创建了附件数组并创建了一个空对象。

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

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

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

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

【问题讨论】:

  • 您想在运行时将元素添加到数组中吗?
  • 您可以创建带参数的构造函数。其中一个参数可以是数组。您的构造函数在参数列表中没有任何参数。

标签: c# arrays


【解决方案1】:

要添加到数组中,你需要在构造之后进行

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

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

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

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

【讨论】:

  • 糟糕,实际上注意到它是一个数组。 Array 没有 Add 方法,您需要使用 List 代替。编辑答案以向创建的数组添加 1 个附加实例。
【解决方案2】:

您可以使用数组初始化器并只添加一项:

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

附带说明,大多数 .NET 命名标准以大写字母开头的属性名称 (Attachments)

【讨论】:

  • 你没想到之前有人问过这个问题?
  • 谢谢,但是我已经在构造函数中初始化了数组,因此它已经有一个数组元素。
  • @DaleFraser 您不能在运行时轻松地“添加”到数组 - 您必须为新的更大数组重新分配空间。要么用新数组覆盖数组,要么使用私有List<T> 并通过属性获取器将其公开为数组。
  • 谢谢,但我没有添加到数组中,数组存在,我只是想设置它,另一个答案是我正在寻找的谢谢。
猜你喜欢
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
相关资源
最近更新 更多