如何初始化构造一个列表? [英] How to initialize a list with constructor?
问题描述
我有一个类型:
public class Human
{
public int Id { get; set; }
public string Address { get; set; }
public string Name { get; set; }
public List<ContactNumber> ContactNumbers { get; set; }
public Human(int id)
{
Id = id;
}
public Human(int id, string address, string name,
List<ContactNumber> contactNumbers) :
this(id)
{
Address = address;
Name = name;
ContactNumbers = contactNumbers;
}
}
请指引我是其中的最佳实践使用的构造与列表初始化? 如何使用构造函数初始化列表?
Please guide me is among best practices to use constructor with for list initialization? How to initialize a list using constructor?
编辑:
请指引我是其中的最佳实践使用的构造与列表初始化? 如何分配值使用构造函数,因此,如果没有值传递一个默认列表将被使用?
Please guide me is among best practices to use constructor with for list initialization? How to assign values to list using a constructor, so if no value passed a default will be used?
感谢
推荐答案
使用集合初始化
从C#3,您可以使用集合初始化构造一个列表,并使用单一的前pression填充它。下面的例子中构造了一个人类及其ContactNumbers:
From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:
var human = new Human(1, "Address", "Name") {
ContactNumbers = new List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
}
}
专业的人
构造
Specializing the Human
constructor
您可以修改人
类的构造函数提供一种方式来填充 ContactNumbers
属性:
You can change the constructor of the Human
class to provide a way to populate the ContactNumbers
property:
public class Human
{
public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
}
// Using the first constructor:
List<ContactNumber> numbers = List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
};
var human = new Human(1, "Address", "Name", numbers);
// Using the second constructor:
var human = new Human(1, "Address", "Name",
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
);
底线
哪个选择是最好的做法?或者至少是一个好的做法呢?你判断它!国际海事组织,最好的做法是写程序尽可能明确地向任何人谁也读它。使用集合初始化是一个胜利者对我来说,在这种情况下。用少得多的code,它几乎可以做同样的事情作为替代品 - 至少,我给了替代品...
Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...
这篇关于如何初始化构造一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!