我创建了一个基类(“element”)和一个基列类(“elements”)作为泛型类。
泛型列表类只能包含从“element”派生的“element”类型的类。
“element”类应该拥有一个“parentroot”属性,该属性应该包含基列表类(“elements”)!

public class Element
{
    public Elements<Element> ParentRoot { get; set; }
}

public class Elements<T> : List<T> where T : Element
{
}

现在我创建了两个类和两个列表类,它们是从上面的类派生的。但我无法设置“parentroot”属性:
public class Ceiling : Element
{
    public Ceiling(Ceilings parent)
    {
        Parent = parent;
        ParentRoot = parent;
    }

    public Ceilings Parent { get; set; }
}

public class Ceilings : Elements<Ceiling>
{
}

public class Wall : Element
{
    public Wall(Walls parent)
    {
        Parent = parent;
        ParentRoot = parent;
    }

    public Walls Parent { get; set; }
}

public class Walls : Elements<Wall>
{
}

我有两个错误:
ParentRoot = parent;

无法将类型“天花板”隐式转换为“元素”
无法将类型“walls”隐式转换为“elements”
这个问题有解决办法吗?
谢谢你的帮助!
编辑:
好吧,我得说得更具体一点。
我把代码扩展了一点:
public class Room
{
    public Room(Rooms parent)
    {
        Parent = parent;
    }

    public Rooms Parent { get; set; }
}

public class Rooms : List<Room>
{

}

public class Element
{
    public Elements<Element> ParentRoot { get; set; }

    public Rooms FindRoomsToElement()
    {
        Rooms rooms = new Rooms();

        foreach (Room room in ParentRoot.Parent.Parent)
        {
            // Do stuff here

            // if i rename the "ParentRoot" property to "Parent" and make it "virtual",
            // and the other properties overwrite it with the "new" key, then this will
            // get a null exception!
            // i haven't testet it, but i think abstrakt will bring the same/similar result

            // if i make the "ParentRoot" property IEnumerable, then there will no
            // ParentRoot.Parent be available
        }

        return rooms;
    }
}

public class Elements<T> : List<T> where T : Element
{
    public Elements(Room parent)
    {
        Parent = parent;
    }

    public Room Parent { get; set; }
}



public class Ceiling : Element
{
    public Ceiling(Ceilings parent)
    {
        Parent = parent;
        //ParentRoot = parent;
    }

    public Ceilings Parent { get; set; }
}

public class Ceilings : Elements<Ceiling>
{
    public Ceilings(Room parent) : base(parent)
    {
    }
}

public class Wall : Element
{
    public Wall(Walls parent)
    {
        Parent = parent;
        //ParentRoot = parent;
    }

    public Walls Parent { get; set; }
}

public class Walls : Elements<Wall>
{
    public Walls(Room parent) : base(parent)
    {
    }
}

我希望这能让它更精确。

最佳答案

不允许这样做,因为如果可以,可能会将错误的元素放入List中。

 Elements<Ceilings> ceilings = someCeilings;
 Elements<Element> parentRoot = ceilings; // Not allowed; imagine it is though.
 Wall wall = someWall;
 parentRoot.Add(wall); // Oops - we just added a wall to someCeilings!

如果您可以将墙和/或天花板视为一个序列,则可以使用IEnumerable<Element>来代替(这是因为IEnumerable<T>是“协变的”):
IEnumerable<Element> parentRoot = ceilings; // OK

这是可以的,因为IEnumerable<Element>无法修改原始集合。

10-01 06:24
查看更多