I want to create customized list in c#. In my customized list I want only create customized function Add(T), other methods should remain unchanged.
When I开发者_如何学运维 do:
public class MyList<T> : List<T> {}
I can only overide 3 functions: Equals, GetHashCode and ToString.
When I do
public class MyList<T> : IList<T> {}
I have to implement all methods.
Thanks
When I do public class MyList : IList {}
I have to implement all methods.
Yes, but it's easy... just send the call to the original implementation.
class MyList<T> : IList<T>
{
    private List<T> list = new List<T>();
    public void Add(T item)
    {
        // your implementation here
    }
    
    // Other methods
    public void Clear() { list.Clear(); }
    // etc...
}
You can have MyList to call List<T> implementation inetrnally, except for Add(T), you'd use Object Composition instead of Class Inheritence, which is also in the preface to the GOF book: "Favor 'object composition' over 'class inheritance'." (Gang of Four 1995:20)
You can another thing again, by using new keyword: 
public class MyList<T> : List<T> 
{
   public new void Add(T prm) 
   {
       //my custom implementation.
   }
}
Bad: The thing that you're restricted on use only of MyList type. Your customized Add will be called only if used by MyList object type.  
Good: With this simple code, you done :)
You could use the decorator pattern for this. Do something like this:
public class MyList<T> : IList<T>
{
    // Keep a normal list that does the job.
    private List<T> m_List = new List<T>();
    // Forward the method call to m_List.
    public Insert(int index, T t) { m_List.Insert(index, t); }
    public Add(T t)
    {
        // Your special handling.
    }
}
Use a private List<T> rather than inheritance, and implement your methods as you like.
EDIT: to get your MyList looped by foreach, all you want is to add GetEnumerator() method
                                        
                                        
                                        
                                        
                                        
                                        
                                        
                                        
 加载中,请稍侯......
      
精彩评论