如何强制转换几个嵌套接口-C#



我有IReport接口。这个接口是通用的,有多个属性,为了不让屏幕膨胀,假设它只有ID属性和T object:

public interface IReport<T>
{
public ind ID {get;}
public T ReportedObject {get;}
/*And more properties I want to see when receiving a report*/
}

现在,我有了另一个界面,它为我的数据库中的一些书建模。
public interface IBook 
{
public string Title {get;}
public int ID {get;}
/*and more*/
}
/*so I made:*/
public interface IReportBook<T> : IReport<T> where T : <IBook>
{}

我有一个异步方法,可以从数据库中获取书籍(以及更多(。我想给它一个"IProgress",这样我就可以监视它:
/*In BookFinder.cs */
public async Task<IBook> FindThisBook(int bookID, IProgress<IReportBook<IBook>>) 
{ 
/*Does somethings*/
}

实施:
//1) The book. This implementation is unique for the UI. 
public class UIBook : SomeClassIMustInheritFrom, IBook 
{
/*This implementations has a lot of methods unique to it*/
}
//2) The book report for the generic book:
public class UIBookReport : IReportBook<UIBook> 
{
/*This implementations has a UIBook property and an ID*/
}

我的目标是能够将IReportBook的不同实现传递给BookFinder,这取决于我是否在控制台、WPF等上。即:

/*in some UI script */
private readonly BookFinder;
public async Task<UIBook > PassBook(IBook bookInLibrary)
{
Progress<UIBookReport> Report = new Progress<UIBookReport>();
Report.ProgressChanged += DoSomething;
var book = await BookFinder.FindThisBook(bookInLibrary.ID, Report); //<--
return book as UIBook;
}
/*---------Again, here's how this method looks:---------*/
/*In BookFinder.cs */
public async Task<IBook> FindThisBook(int bookID, IProgress<IReportBook<IBook>>) 
{ 
/*Does somethings*/
}
/*is there a way to just say 
IProgress<IReportBook> 
instead of
IProgress<IReportBook<IBook>>
? because all IReportBooks use IBook...
*/

我的错误是:

。。。无法将类型"X"转换为"Y"。。。通过引用转换、装箱转换、包装转换或null类型转换。。。

我应该做什么类型的铸造?有没有什么错误或方法可以简化这整件事?谢谢

基本上我改变了3件事。


1( 我创建了一个继承自Progress的类
public class BookProgress : Progress<IBookReport>
{
//Left it blank
}

2( 实现了名为UIBookReport的IBookReport

public interface IBook {}
public class UIBook : IBook {}
public interface IReport<T> {}
public interface IBookReport : IReport<IBook>{}
public class UIBookReport : IBookReport {}

3(

/*--------- in the ui*/
public UIBook PassBook(IBook bookInLibrary)
{
BookFinder bookFinder = new BookFinder();
BookProgress progress = new BookProgress();
progress.ProgressChanged += DoSomething;
var book = await bookFinder.FindThisBook(bookInLibrary.ID, progress); //<--
return book as UIBook;
}
/*-------- In BookFinder.cs*/
public async Task<Book> FindBook(int bookID, IProgress<IBookReport> progress) 
{
/*Do stuff*/
var GenericBookReport = AppFactory.GetBookReport(/*some args*/);
//AppFacotry is a script that returns the right implementation of some interfaces depending of the circumstances
//In this case, it returns an UIBookReport (the class)
progress.Report(GenericBookReport);
/*more stuff*/
}

最新更新