Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can't i overload List's Add method ?

class ListDemo<T>:List<T>
 {
    public override T  Add<T>(T value)
   {
      return base.Add(value);
   }
}

I am receiving the following error :

1) Type parameter 'T' has the same name as the type parameter from outer type 'CollectionsExample.ListDemo

2) 'CollectionsExample.ListDemo.Add(T)': no suitable method found to override

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
706 views
Welcome To Ask or Share your Answers For Others

1 Answer

Instead of subclassing from List<T>, you should encapsulate List<T> and implement IList<T>. This makes it easy to handle "overriding" the behavior of Add:

public class ListDemo<T> : IList<T>
{
    private List<T> list = new List<T>(); // Internal list
    public void Add(T item)
    {
       // Do your pre-add logic here
       list.Add(item); // add to the internal list
       // Do your post-add logic here
    }

    // Implement all IList<T> methods, just passing through to list, such as:
}

List<T> should not be part of your public API - it should be an implementation detail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...