Common base class inheriting from a common interface

For some reason, I am struggling to implement a property from a common interface, using a common base class as follows:

public interface IParent<TChild> where TChild : IChild
{
    TChild Child { get; }
}

public interface IChild { }

Then I have a base class:

public class ParentBase<TChild> : IParent<TChild> where TChild : IChild
{
    private TChild _child;
    public ParentBase(TChild child)
    {
        this._child = child;
    }
    #region IParent<TChild> Members

    public TChild Child
    {
        get { return _child; }
    }

    #endregion
}

Now I have a new parent derivative and child as follows:

public class MyChild : IChild { }

public class MyParent : ParentBase<MyChild>, IParent<IChild> 
{
    public MyParent(MyChild child)
        : base(child)
    {
    }
}

I want to create an instance and get an abstract (interface type) in order to convey the following to consumers:

IParent<IChild> parent = new MyParent(new MyChild());

But for some reason I cannot implement TChild correctly, although I defined the property public TChild Childin ParentBase, the compiler says that it is not implemented, even if I try to implement it explicitly. Since you can see that the constraints are fully consistent with the base class.

+5
source share
3 answers

MyParent ParentBase<MyChild> IParent<IChild>.

IParent<IChild> { IChild Child{get; } }

public class MyParent : ParentBase<MyChild>, IParent<IChild>
{
    public MyParent(MyChild child)
        : base(child)
    {
    }

    #region Implementation of IParent<IChild>

    IChild IParent<IChild>.Child
    { 
        get { return base.Child; }
    }

    #endregion
}

IParent :

public interface IParent<out TChild> where TChild : IChild
{
    TChild Child { get; }
}

IParent<IChild> parent = new MyParent(new MyChild());

ParentBase<MyChild> parent2 = new MyParent(new MyChild());

IParent<IChild> parent3 = parent2;

@svick, , IParent<IChild> .

+4

, . IParent interafce :

public interface IParent<out TChild> where TChild : IChild

IParent<IChild> MyParent:

public class MyParent : ParentBase<MyChild>

MyParent , IParent<IChild>. , , :

MyParent parent = new MyParent(new MyChild());
IParent<IChild> iParent = parent;
+3

IChild, TChild, ?

public interface IParent
{
    public IChild Child { get; }
}

public class ParentBase<TChild> : IParent where TChild : IChild
{
    public IChild Child { get { return myChild; } }
}

public class MyParent : ParentBase<MyChild> // already implements IParent by the base doing so.
{
}
0

All Articles