Covariance in generic interfaces

后端 未结 3 1284
傲寒
傲寒 2021-01-13 05:17

I wanted to create an observableCollection that is sortable so i started creating a class that inherit observable with some methods to sort it, then i wanted that class to p

3条回答
  •  不知归路
    2021-01-13 05:57

    You need DerivedClass to be a ISortable:

    public class DerivedClass : BaseClass, ISortable
    {
        public new ISortableCollection ParentCollection
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }
    }
    

    Co- and contravariance on T cannot work here because you are deriving from IList which is invariant.

    Even removing IList and removing the getter I can't get it to work right now with variance. Not exactly a strength of mine. This is a part of the type system that is better left alone if you can help it.

    If the type system makes your head explode consider a dynamic solution:

    ((dynamic))item).ParentCollection = this;
    

提交回复
热议问题