基本上我希望能够执行以下操作,但我认为我的类层次结构设计错误,或者我错过了与多态性/泛型集合相关的一些重要内容:
ISearchableMediaList<IMedia> list = new MovieList();
上面的行产生以下错误:Cannot implicitly convert type 'MovieList' to 'ISearchableMediaList<IMedia>'. An explicit conversion exists (are you missing a cast?)
。我不应该能够在不强制转换的情况下用派生类型替换接口吗?(有关详细信息,请参阅底部的类图)。
public interface IMedia
{
string Title { get; set; }
double Rating { get; set; }
DateTime Date { get; set; }
string Comments { get; set; }
}
public class Media : IMedia { ... }
public class Movie : Media { // Adds on movie-specific properties }
public class Book : Media { // Adds on book-specific properties }
public interface IMediaList<T> : ISearchableMediaList<T> where T : IMedia
{ ... }
public interface ISearchableMediaList<T> : IList<T> where T : IMedia
{
IList<string> SearchCategories { get; }
IList<T> Search(string query, string category);
}
public class MediaList<T> : BindingList<T>, IMediaList<T> where T : IMedia
{
// Implements common search functionality and other stuff
}
public class MovieList : MediaList<Movie>
{
// Implements movie-specific searching and other stuff
}
public class BookList : MediaList<Book>
{
// Implements book-specific searching and other stuff
}