I wanted to create an observable set that can be sorted, so I started creating a class that inherits observables using some methods to sort it, then I wanted this class to store the index in its children, so I created an interface that exposes the index property, in which I can write, and I rated T of my collection class to be from my interface, then I wanted to be able to access parentCollection from any element, and here the problems started, because the type of the parent collection is explicit is Busy general ... I tried a lot of solutions, and I think that the covariance and invariance - is a way, but I can not get it to work ...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class SortableCollection<T> : System.Collections.ObjectModel.ObservableCollection<T>, ISortableCollection<T> where T : ISortable<T>
{
public void Sort()
{
throw new NotImplementedException();
}
protected override void InsertItem(int index, T item)
{
item.Index = index;
item.ParentCollection = this;
base.InsertItem(index, item);
}
}
public interface ISortableCollection<T> : IList<T>
{
void Sort();
}
public interface ISortable<T>
{
Int32 Index { get; set; }
ISortableCollection<T> ParentCollection { get; set; }
}
public class BaseClass : ISortable<BaseClass>
{
public int Index { get; set; }
public ISortableCollection<BaseClass> ParentCollection { get; set; }
}
public class DerivedClass : BaseClass { }
public class Controller
{
SortableCollection<BaseClass> MyBaseSortableList = new SortableCollection<BaseClass>();
SortableCollection<DerivedClass> MyDerivedSortableList = new SortableCollection<DerivedClass>();
public Controller()
{
}
}
}
.
SortableCollection<DerivedClass>, ... ?
1 "ClassLibrary1.DerivedClass" "T" 'ClassLibrary1.SortableCollection<T>'. ClassLibrary1.DerivedClass 'ClassLibrary1.ISortable<ClassLibrary1.DerivedClass>'. c:\users\luigi.trabacchin\\visual studio 2013\Projects\ClassLibrary1\ClassLibrary1\Class1.cs 48 89 ClassLibrary1