基本上我希望能夠做到以下幾點,但我認爲我設計我的類層次結構錯誤或我缺少多態性/泛型集合東西相關的關鍵:多態性/子類型違規?
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
}
可能重複鑄造(http://stackoverflow.com/questions/8402805/generics-covariance-and-explicit-casting) –
MovieList或BookList是否提供超出MediaList的任何其他功能? –
nerdybeardo
@Moe:是的,它實現了特定於媒體類型的搜索功能以及其他內容。 – Brett