Generics, abstract classes, constructors

I have an abstract base class

class AbstractClass 
{
    Col<AbstractClass> parent

    public AbstractClass()
    {
        //do stuff
    }
}

I have two implementations

class A : AbstractClass 
{ 
    Col<A> parent

    public A(Col<A> parent)
        :base(parent)
    {
        this.parent = parent;
    }  

}

class B : AbstractClass 
{ 
    Col<B> parent

    public B(Col<B> parent)
        :base(parent)
    {
        this.parent = parent;
    }
}

I have a collection

class Col<T> : IList<T> where T : AbstractClass

What should be used in another class like Col<A> and Col<B>, let this class C.

class C
{
    List<A> a = new List<A>()
    List<B> b = new List<B>()
}

All of this will work, except that I want to type A, and Bwere aware of its parent collection. I thought the following constructors in AbstractClass, A, B would be fine, but it seems that general restrictions are only available for classes, not methods. In fact, I would like the following constructors:

public AbstractClass(Col<T> where T : AbstractClass)
public A(Col<A>)
public B(Col<B>)

instances of A, B should know what collection they are in, but I can not call the base constructor from derived classes, because they are different types.

Help!

+3
4

, ++ , - :

abstract class AbstractClass<TDerivedClass>
    where TDerivedClass : AbstractClass<TDerivedClass>
{
    Col<TDerivedClass> parent;

    public AbstractClass(Col<TDerivedClass> parent)
    {
        // do stuff
        this.parent = parent;
    }
}

class A : AbstractClass<A>
{ 
    public A(Col<A> parent)
        :base(parent) {}
}

class B : AbstractClass<B>
{ 
    public A(Col<B> parent)
        :base(parent) {}
}
+4

, A B

. XML ,

+1

Use your own Collection<T>type instead List<T>. They basically provide the same functionality ( Collection<T>uses List<T>internally) and is designed specifically for these purposes.

You can then override InsertItemto set the parent of any item added to the collection.

public class MyCollection<T> : System.Collections.ObjectModel.Collection<T>
{
    protected override void InsertItem(int index, T item)
    {
        base.InsertItem(index, item);
        item.Parent = this;
    }
}
+1
source

Source: https://habr.com/ru/post/1716091/


All Articles