gpt4 book ai didi

C#:List 的继承问题

转载 作者:太空狗 更新时间:2023-10-29 22:04:39 25 4
gpt4 key购买 nike

让我们在 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);
}
}

编译器在“public void Add(T value)”行中给我这个警告:

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

我该怎么做才能避免出现此警告?

感谢 4 你的帮助

最佳答案

否 - 不要使用 new这里;那不会给你多态性。 List<T>不打算以这种方式继承;使用 Collection<T>override Add InsertItem方法。

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#:List<T> 的继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/898152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com