gpt4 book ai didi

c# - 动态实例化 List

转载 作者:行者123 更新时间:2023-11-30 20:06:38 24 4
gpt4 key购买 nike

全部 -

我正在尝试动态地(在运行时)创建一个具有 3 个属性的人员集合 - 姓名、技能组和地址集合。

我面临的问题是我无法在实例化时在下一行中添加地址。

people.Add(new Person() { Name = "John Smith", Skillset = "Developer", _________ });

所以基本上我如何将这 3 行合并为 1 行以便我可以在上面传递它:

Person per = new Person();
per.Complete_Add = new List<Address>();
per.Complete_Add.Add(new Address("a", "b"));

这是我的完整程序:

class Program
{
static void Main(string[] args)
{
PersonViewModel personViewModel = new PersonViewModel();
}
}

public class Person
{
public string Name { get; set; }
public string Skillset { get; set; }
public List<Address> _address;
public List<Address> Complete_Add
{
get { return _address; }
set { _address = value; }
}
}

public class Address
{
public string HomeAddress { get; set; }
public string OfficeAddress { get; set; }

public Address(string _homeadd, string _officeadd)
{
HomeAddress = _homeadd;
OfficeAddress = _officeadd;
}

}

public class PersonViewModel
{
public PersonViewModel()
{
people = new List<Person>();
Person per = new Person(); \\Dont want to do this
per.Complete_Add = new List<Address>(); \\Dont want to do this
per.Complete_Add.Add(new Address("a", "b")); \\Dont want to do this
people.Add(new Person() { Name = "John Smith", Skillset = "Developer", Complete_Add = per.Complete_Add });
people.Add(new Person() { Name = "Mary Jane", Skillset = "Manager" });
people.Add(new Person() { Name = null, Skillset = null });
}

public List<Person> people
{
get;
set;
}
}

最佳答案

你仍然可以通过属性初始化器来完成

 people.Add(new Person() { Name = "John Smith", Skillset = "Developer", 
Complete_Add = new List<Address>
{
new Address("a", "b")
}});

关于c# - 动态实例化 List<I>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9574233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com