c# 无论如何要向 List<Type> 添加其他方法?

Cal*_*tor -1 c#

问题

我有 Point2D 类作为基类,用于存储我通常使用的点列表,List<Point2D>但现在我想添加其他方法和很少的属性来List<Point2D>喜欢 ToString 打印方法,根据特定坐标排序,过滤点的特定方法,我不不想使用扩展方法。

我尝试过的事情

我创建了一个Point2DList继承List<Point2D>类的新类,该类可以正常使用,但是当使用 FindAll 函数时,它现在返回List<Point2D>但我希望它返回Point2DList。我知道我可以编写自己的方法来接受谓词委托,但这工作量太大了。

代码

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleAppTest
{
    internal static class Program
    {
        private static void Main()
        {
            try
            {
                var points = new Point2DList();
                points.Add(new Point2D(0, 0));
                points.Add(new Point2D(10, 0));
                points.Add(new Point2D(10, 10));
                points.Add(new Point2D(0, 10));
                Console.WriteLine(points.ToString());
                Point2DList newPoints = points.FindAll((x) => x.X == 10);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }

    public class Point2DList : List<Point2D>
    {
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendLine("List of Points");
            foreach (var pt in this)
            {
                sb.AppendLine(pt.ToString());
            }
            return sb.Remove(sb.Length - 1, 1).ToString();
        }
    }

    public class Point2D
    {
        public int X { get; set; }
        public int Y { get; set; }

        public Point2D(int x, int y)
        {
            X = x;
            Y = y;
        }

        public override string ToString()
        {
            return $"{X},{Y}";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Him*_*ere 5

It's很少neccessary来继承,从任何集合型-特别是当你只想程度上它,而不是改变它的实现。因此,我会通过继承进行组合并使用字段代替:

class Points2DList
{
    private List<Point2D> _points;

    public Points2DList(List<Point2D> points) { _points = points; } 

    public override string ToString() { ...}

    public void Add(Point2D p { _points.Add(p); } // delegate to implementation of your underlying list

    public Point2D this[int i] // delegate to implementation of your underlying list
    { 
        get => _points[i]; 
        set => _points[i] = value; 
    }

    public Points2DList FindAll(Predicate<Point2D> P) 
    {
        return new Points2DList(_list.FindAll(p));// delegate to implementation of your underlying list
    }
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以控制您真正想要向客户公开哪些功能。使用继承会将每个公共成员暴露给外部,这是您可能不想要的。例如,虽然您希望允许从列表中删除一个元素,但您可能不想让客户端能够调用Clear它。