I created a base class ("Element") and a base list class ("Elements") as generic class.
The generic list class should only be able to contain classes, which are of Type "Element" of derived from "Element".
The "Element" class should own a "ParentRoot" property, which should contain the base list class ("Elements")!
public class Element
{
public Elements<Element> ParentRoot { get; set; }
}
public class Elements<T> : List<T> where T : Element
{
}
Now i create two classes and two list classes which are derived form the classes above. But i'm failing on setting the "ParentRoot" property:
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>
{
}
I get two errors at:
ParentRoot = parent;
Cannot implicitly convert type "Ceilings" to "Elements"
Cannot implicitly convert type "Walls" to "Elements"
Is there a solution for this problem?
Thanks for any help!
EDIT:
OK, i have to be a bit more specific.
I expanded the code a bit:
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)
{
}
}
I hope this makes it more precise.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…