如何创建包含抽象元素列表的集合类



我需要创建一个包含抽象段列表的集合。

我有许多来自分段的派生类,即LineSegment : Segment

public class Path : IEnumerable
{
        private List<Segment> segments = new List<Segment>();

        public List<Segment> Segments 
        {  
            set { Segments = value;}
            get { return this.segments; } 
        }
        //some code inc ctrs
}

我希望能够将LinePath定义为基类Path 的派生类

public class LinePath : Path, IEnumerable
{        
        public LinePath(List<LineSegment> s)
        {
            this.Segments = s; //error
        }
}

然而,我经常遇到这样的情况:我无法轻松编辑LinePath的包含,因为它包含的列表仍然是Segment列表(大量铸造),或者当我希望从LinePath加上其他派生段创建一个普通的Path时。

这类问题的标准格式是什么?也许我应该放弃LinePath,只使用Path对象?

我意识到这个问题可能有点模糊,我对此道歉,但需要弄清楚到底是什么导致了我的困惑,避免混乱的解决方案。

我看到了几个选项。首先,寻找将列表用作IEnumerable<T>而不是List<T>的机会,因为List<LineSegment>可以用作IEnumerable<Segment>,只需强制转换列表,而不必强制转换所有元素(假设C#4.0或更高版本)。

其次,考虑将Path从Segment派生(如果愿意的话,PathSegment),这样就可以将LinePath作为单个对象包含在Path中,而不是将其所有LineSegment元素添加到Path的Segment图元列表中。

您可能想在codereview.stackeexchange.com.

上发布更大的代码摘录

我不知道我是否正确理解了这个问题,但我认为这是你想要的行为。

public class GenericPath<T> : IEnumerable
    {
        private List<T> items = new List<T>();

        public List<T> Items
        {
            set { this.items = value; }
            get { return this.items; }
        }
        //some code inc ctrs
    }
    public class Segment
    {
    }
    public class Path : GenericPath<Segment>
    {        
    }
    public class LinePath : GenericPath<Path>
    {
    }

我认为最好定义泛型参数T应该是Segment类型。为了避免类似Path<string>的事情。

此外,您不需要从IEnumerable继承LinePath,它将从Path继承此接口实现。并考虑使用通用版本的IEnumerable接口。

  public class Path<T> : IEnumerable<T>
        where T : Segment // here we define that parameter is Segment or its child
    {
        private List<T> _segments = new List<T>();        
        public List<T> Segments
        {
            set { _segments = value; }
            get { return _segments; }
        }
        public IEnumerator GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
    public class LinePath<T> : Path<T> 
        where T : LineSegment // parameter is LineSegment or its child
    {
        public LinePath(List<T> segments)
        {
            // no error because Path.Segments of type List<LineSegment>
            Segments = segments;
        }
    }

最新更新