简体   繁体   中英

Can I initialize a derived class with an instance of the base class?

Example:

public class MyList<T> : List<T> {
    public MyList(List<T> list) {
        this = list;  // this is basically what I want, but doesn't work
        base = list;  // this also doesn't work
    }
}

Any solutions? Or is what I'm trying to achieve simply a bad idea?

Motivation: I want to add a custom function to a List object.

If your using .Net framework 3.5, wouldn't it be easier to define an extension method on a list. Somthing like...

public static class MyListExtensionClass
{
    public static void MyList<T>(this List<T> list)
    {
        // Your stuff
    }
}

Can you not do:

public MyList(List<T> list) : base(list)

Alternatively, couldn't you use an extension method on the List object?

public MyList(List list):base(list)

This will call the following constructor of the base class (in this case List):

public List(IEnumerable<T> collection);
public class MyList<T> : List<T>
{
  public MyList(List<T> list)
  {
    AddRange(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