简体   繁体   中英

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.

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:

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

I assume you want the .ctor argument to be added to the list. 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#:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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