简体   繁体   English

List的子类的构造方法 <T> C#

[英]Constructor for a subclass of List<T> C#

This is my class: 这是我的课:

public class CustomList: List<SomeType>{

 SomeType myList;

 public CustomList(List<SomeType> list){
  myList = list;
 }

//some methods
}

and I initialise it like this: 我这样初始化它:

CustomList myCustomList = new CustomList(someList);

However upon accessing the first member of the list ( myCustomList[0] ) i get: AurgumentOutOfRangeException error. 但是,在访问列表的第一个成员( myCustomList[0] )时,我得到:AurgumentOutOfRangeException错误。

Am I doing anything wrong in my custom list constructor and/or initialisation? 我在自定义列表构造函数和/或初始化中做错什么了吗?

Appreciate your help. 感谢您的帮助。

Edit: 编辑:

SomeType is a class consist of some public variables: SomeType是一个由一些公共变量组成的类:

public class SomeType{
 public string title;
 public string campaign;
}

I assume you want the .ctor argument to be added to the list. 我假设您希望将.ctor参数添加到列表中。 So add it... 所以添加...

public class CustomList: List<SomeType>{

 public CustomList(List<SomeType> list){
  this.AddRange(list);
 }

//some methods
}

As Alexei pointed out in the comments an alternative method of calling the base class .ctor using this syntax in C#: 正如Alexei在评论中指出的,使用C#中的以下语法调用基类.ctor的另一种方法:

public class CustomList : List<SomeType> {
    public CustomList(List<SomeType> list) : base(list) { ... }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM