【问题标题】:put the value inside the array inside a class将值放入类中的数组中
【发布时间】:2023-03-21 06:01:01
【问题描述】:

我有以下课程:

public class test100
{
     public string dateofbirth{ get; set; }
     public string phonenumber{ get; set; }

     public Name[] names { get; set; }

}

我想为名称赋值,然后将该值添加到 test100 类中。我不想创建列表。我只想用一个数组来做这个。我想把这样的值:

names[0] = {firstName="test1", MiddleName="test2", lastName="test3"}

然后将 names[0] 添加到 test100 类。

我怎样才能做到这一点。

【问题讨论】:

  • 恕我直言,请使用List<T> 执行此操作。
  • 没有清单就不行
  • 是的,有可能,你为什么选择数组?
  • 如果您使用List<T>,您可以执行以下操作:Name.Add(new Name(){.firstName="somebody"}); 此外,如果您不知道您使用了多少Name,您将不知道数组的大小,使用List<T> 你不需要知道大小。
  • 我正在尝试创建一个 JSON,我想要类似 "test100": [ { "names": { "personDetails": { "firstName": "test1", :MiddleName= }, I认为这只有在数组不是列表的情况下才有可能

标签: c# arrays class


【解决方案1】:

你可以在初始化类本身的同时初始化数组

var data = new test100
{
  dateofbirth = "22-03-1997",
  phonenumber = "1-223344",
  names = new Name[] 
  {
    new Name {firstName="test1", MiddleName="test2", lastName="test3"}
  }
}

问题在于您没有为names 数组定义任何大小。因此,您可以创建类的实例,定义该数组的大小,然后将对象插入该数组

var data = new test100();
data.names = new Name[10];
Name name = new Name {firstName="test1", MiddleName="test2", lastName="test3"};
data.names[0] = name;

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 2023-03-14
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多