Problems with inherited classes, constructors with generics

I have a semi-complex inheritance structure that is hard for me to deal with overriding the constructor in the base class. The following code may show an error:

public abstract class MyBaseObject
{
    public MyBaseObject(MyBaseCollection<MyBaseObject> parent)
    {
        this.Parent = parent;
    }

    public MyBaseCollection<MyBaseObject> Parent { get; set; }
}

public abstract class MyBaseCollection<T>
    where T : MyBaseObject
{ }

public class MyRealObject : MyBaseObject
{
    public MyRealObject(MyRealCollection parent)
        : base(parent)
    { }

    public new MyRealCollection Parent { get { return (MyRealCollection)base.Parent; } }
}

public class MyRealCollection : MyBaseCollection<MyRealObject>
{ }

Therefore, in particular, I cannot override the constructor in the MyBaseObject class. Trying to switch to MyRealCollection instead of MyBaseCollection is not acceptable. If I get rid of the generics arguments, it will work; MyRealCollection is accepted instead of MyBaseCollection. But I really need the generics argument so that my collection classes work the way I need them.

+3
source share
2 answers

. http://msdn.microsoft.com/en-us/library/dd799517.aspx

, CLR , , , .

- , . IEnumerable, .

public abstract class MyBaseObject
{
    public MyBaseObject(IEnumerable<MyBaseObject> parent)
    {
        this.Parent = parent;
    }

    public IEnumerable<MyBaseObject> Parent { get; set; }
}

public class MyRealObject : MyBaseObject
{ 
    public MyRealObject(MyRealCollection parent)
        : base(parent)
    { }

    public new MyRealCollection Parent { get { return (MyRealCollection)base.Parent; } }
}

public class MyRealCollection : IEnumerable<MyRealObject>
{ }
+3

MyRealCollection MyBaseCollection, MyRealObject, MyBaseObject. , , , MyBaseObject :

public MyBaseObject(MyBaseCollection<MyBaseObject> parent)
{
    this.Parent = parent;
    parent.Add(new SomeOtherRealObject());
}

MyBaseObject, MyRealCollection

+3
source

All Articles