c# - 继承List<T>时如何在没有构造函数的情况下将数据传递给父类? C#

标签 c# .net

我正在查看一个继承了 List<T> 的代码.为继承 List<T> 的子类创建对象时, 传递了两个 T 类型的值。

那两个对象是如何到达父类的List<T> ?据我所知,您需要一个构造函数,该构造函数使用 :base() 将参数传递给父级的构造函数。 ,但就我而言,没有任何 base在任何地方指定。

这是我的类(class)

public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}

public class PeopleCollection : List<Person>
{

}

现在假设我有两个 Person 类型的对象命名为 p1, p2

我关心的是下面这行..

PeopleCollection people = new PeopleCollection { p1, p2 };

PeopleCollection 中没有构造函数它需要一个 Type Person 的集合。然而传递了两个对象。

我想知道的是,在继承 List<T> 时是否有默认行为?当您为继承 List<T> 的类创建对象时,它会自动将值添加到父项 List<T> ?如果不是那么上面的代码是如何工作的?自 PeopleCollection 以来 p1 和 p2 存储在哪里没有自己的收藏?

最佳答案

此技术称为 Collection Initializers并且它与问题中提到的构造函数无关。

Collection initializers let you specify one or more element initializers when you initialize a collection type that implements IEnumerable and has Add with the appropriate signature as an instance method or an extension method. The element initializers can be a simple value, an expression, or an object initializer. By using a collection initializer, you do not have to specify multiple calls; the compiler adds the calls automatically.

关于c# - 继承List<T>时如何在没有构造函数的情况下将数据传递给父类? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508015/

相关文章:

c# - 为什么我在连接到 wcf 服务时看到 "HTTP Error 400. The request hostname is invalid."

c# - 组合键匹配的多个字典

.net - 为手动选择的行放置 DataGridView 的行指示器

c# - 允许空值时如何将 nvarchar(x) 读入 String?

.net - Windows Azure 跟踪日志不工作

python - pypy import clr 在 Windows 上失败

c# - 通过右键单击桌面或目录背景创建 Shell ContextMenu

c# - Async GetAwaiter() 抛出奇怪的异常

c# - 由于 CORS,Angular 请求无法访问 API 控制

c# - 如何更改计划任务的内存优先级?