我想创建一个可排序的observableCollection,所以我开始创建一个继承observable的类,并添加了一些方法来对其进行排序,然后我希望该类能将索引保留到子项中,所以我创建了一个公开索引属性的接口,并将我的集合类T约束为我的接口类型,然后我希望能够从每个项中访问parentCollection,但由于父集合的类型是泛型,所以问题就出现了... 我尝试了很多解决方案,我认为协变或不变性可能是解决问题的方法,但我无法使其正常工作...
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()
{
//We all know how to sort something
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()
{
//do things
}
}
}
这是大致的设置。我想创建一个
SortableCollection<DerivedClass>
,但类型不匹配...应该如何正确处理?确切的错误信息是:
“错误1 类型'ClassLibrary1.DerivedClass'不能用作泛型类型或方法'ClassLibrary1.SortableCollection<T>'中的类型参数'T'。没有从'ClassLibrary1.DerivedClass'到'ClassLibrary1.ISortable<ClassLibrary1.DerivedClass>'的隐式引用转换。c:\users\luigi.trabacchin\documents\visual studio 2013\Projects\ClassLibrary1\ClassLibrary1\Class1.cs 48 89 ClassLibrary1”