问题描述
我正在尝试在编写应用程序时遇到的问题(我)问题。
请看这个,请(为了简单起见,我会尝试缩短代码):
I'm trying to overrun quite big (for me) problem that I came across while writing my application.Look at this, please (I will try to shorten the code for simplicity):
我有一个名为的根界面IRepository< T> ;
。
接下来, IBookRepository:IRepository< Book>
接下来,实现它的具体类: BookRepository:IBookRepository
在RepositoryManager类中,我声明了 private IRepository< IRepoItem> currentRepo;
In the RepositoryManager class I declared private IRepository<IRepoItem> currentRepo;
IRepoItem
是一个由Book类实现的接口。
IRepoItem
is an interface that is implemented by Book class.
现在,当我尝试这样做时:
Now, when I try to do something like this:
currentRepo = new BookRepository();
VisualStudio提供错误消息:
VisualStudio gives error message:
我试图显式转换,但抛出运行时异常...
I tried to cast explicitly, but runtime exception is thrown...
我知道(几乎可以肯定)这是一种叫做协方差的东西,这可能(可能)在.Net 4.0中解决了。
不幸的是我正在使用框架版本3.5编写,我无法改变它。请给我一些建议 - 如何超支这个问题?我想从RepoFactory获得currentRepo,它会产生几种存储库,具体取决于用户的需求。我不知道这里是否允许链接,但是我在我描述了应用程序创建。我的英语不好,但我希望能理解我。提前感谢您的回答。
I know (almost for sure) that it is something called covariance and this is (probably) solved in .Net 4.0.Unfortunately I'm writing using framework version 3.5, and I cannot change this. Please give me some advices what to do - how to overrun this problem? I'd like to get currentRepo from RepoFactory that would produce few kinds of repositories depends on user needs. I don't know whether links are allowed here, but I write some kind of blog on http://olgatherer.wordpress.com/ where I describe application creation. My English isn't good, but I hope that it's enough to understand me. Thank you in advance for answer.
祝你好运,
skrzeczowas
Best regards,skrzeczowas
推荐答案
在.NET 3.5中,您绝对不能将 IRepository< Book>
视为 IRepository< IRepoItem>
。
In .NET 3.5 you definitely can't treat an IRepository<Book>
as an IRepository<IRepoItem>
.
我们需要更多地了解您在 RepositoryManager
中使用存储库的内容真的知道如何解决它...但是你能创建一个非通用的 IRepository
接口,其中 IRepository< T>
扩展?使其包含所有不引用T的成员。然后,您可以将 currentRepo
声明为 IRepository
。
We'd need to know more about what you're using the repository for in RepositoryManager
to really know how to solve it... but could you create a non-generic IRepository
interface which IRepository<T>
extends? Make it include all the members which don't refer to T. Then you can declare currentRepo
as just an IRepository
.
这篇关于C#中的接口继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!