重载列表< T>的添加() [英] Overriding List<T>'s Add()

查看:140
本文介绍了重载列表< T>的添加()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能重载列表的Add方法

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)类型参数'T'具有相同的名称从外部类型类型参数'CollectionsExample.ListDemo

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

2) CollectionsExample.ListDemo.Add(T):找到重写

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

推荐答案

没有合适的方法列表< T> ,您应该封装列表< T> 和实施的IList< T> 。这使得它易于处理压倒一切添加的行为:

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:
}



列表< T> 不应该是你的公共API的一部分 - 它应该是一个实现细节

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

这篇关于重载列表&LT; T&GT;的添加()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆