C#:与名单,其中继承问题; T> [英] C#: Inheritance Problem with List<T>

查看:148
本文介绍了C#:与名单,其中继承问题; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设这个类在C#:<​​/ P>

Let's assume this class in C#:

public class LimitedList<T> : List<T>
{
    private int _maxitems = 500;

    public void Add(T value) /* Adding a new Value to the buffer */
    {
        base.Add(value);
        TrimData(); /* Delete old data if lenght too long */
    }

    private void TrimData()
    {
        int num = Math.Max(0, base.Count - _maxitems);
        base.RemoveRange(0, num);
    }
}

编译器给了我这个警告在该行公共无效添加(T值):

The compiler gives me this warning in the line "public void Add(T value)":

警告CS0108:System.LimitedList.Add(T)隐藏了继承的成员System.Collections.Generic.List.Add(T)。使用new关键字,如果隐藏之意。

warning CS0108: 'System.LimitedList.Add(T)' hides inherited member 'System.Collections.Generic.List.Add(T)'. Use the new keyword if hiding was intended.

什么我必须做的,以避免这样的警告?

What do I have to do to avoid this warning?

THX 4你的帮助

推荐答案

没有 - 不要使用在这里;这不给你多态。 名单,其中,T&GT; 不适合继承这种方式;使用收藏&LT; T&GT; 覆盖 添加 InsertItem 方法。

No - don't use new here; that doesn't give you polymorphism. List<T> isn't intended for inheritance in this way; use Collection<T> and override the Add InsertItem method.

public class LimitedCollection<T> : Collection<T>
{
    private int _maxitems = 500;

    protected override void InsertItem(int index, T item)
    {
        base.InsertItem(index, item);
        TrimData(); /* Delete old data if lenght too long */
    }

    private void TrimData()
    {
        int num = Math.Max(0, base.Count - _maxitems);
        while (num > 0)
        {
            base.RemoveAt(0);
            num--;
        }
    }
}

这篇关于C#:与名单,其中继承问题; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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