Reputation: 7440
I have the following interface representing a hierarchical data structure hence the name IHierachicalItem
public interface IHierachicalItem
{
IHierachicalItem Parent { get; set; }
IList<IHierachicalItem> Children { get; set; }
}
Now I have multiple classes that inherits from this interface:
public class HierachicalItemA : IHierachicalItem
{
public IHierachicalItem Parent { get; set; }
public IList<IHierachicalItem> Children { get; set; }
}
public class HierachicalItemB : IHierachicalItem
{
public IHierachicalItem Parent { get; set; }
public IList<IHierachicalItem> Children { get; set; }
}
public class HierachicalItemC : IHierachicalItem
{
public IHierachicalItem Parent { get; set; }
public IList<IHierachicalItem> Children { get; set; }
}
I wanted to extend the interface so that the classes return upon accessing its parent and children property the same class instead of the interface. So I thought about using a generic interface:
public interface IHierachicalItem<T> : IHierachicalItem
{
new T Parent { get; set; }
new IList<T> Children { get; set; }
}
Now I am facing the problem that I only want to have one instance of Children and don't call something like .OfType.ToList(). How can I achieve this?
public class HierachicalItemB : IHierachicalItem<HierachicalItemB>
{
IHierachicalItem IHierachicalItem.Parent { get { return this.Parent as IHierachicalItem; } set { this.Parent = (HierachicalItemB)value; } }
IList<IHierachicalItem> IHierachicalItem.Children { get { return this.Children.OfType<IHierachicalItem>().ToList(); } set { this.Children = value.OfType<HierachicalItemB>().ToList(); } }
public HierachicalItemB Parent { get; set; }
public IList<HierachicalItemB> Children { get; set; }
}
I also could have used .Cast<> instead of .OfType<> but this doesn't change the the fact that I would have to call .ToList() or if the Interface would say its an ObersavbleCollection again and again init a new ObservableCollection, any ideas?
Upvotes: 3
Views: 97
Reputation: 156988
You can't. Your IHierachicalItem
interface demands a property with the signature IList<IHierachicalItem> Children
, while IHierachicalItem<T>
demands IList<T> Children
. You need both properties implemented. This is the same for your other property.
That is why you need the implicit interface implementation to tell the compiler you comply to both interfaces. There is no way to workaround this, besides of dropping one of the interfaces.
Note: I think you T
should be restricted to the IHierachicalItem<T>
type:
public interface IHierachicalItem<T> : IHierachicalItem where T : IHierachicalItem
Upvotes: 1