问题描述
给定这些接口和类...
Given these interfaces and classes...
public interface IPage
{
string PageTitle { get; set; }
string PageContent { get; set; }
}
public abstract class Page
: IPage
{
public string PageTitle { get; set; }
public string PageContent { get; set; }
}
public class AboutPage
: Page
, IPage
{
}
public interface IPageAdminViewModel<out T>
where T : IPage
{
IEnumerable<T> Pages { get; }
}
public abstract class PageAdminViewModel<T>
: IPageAdminViewModel<T>
where T: IPage
{
public IEnumerable<T> Pages { get; set; }
}
为什么使用 IPage
作为接口类型参数不编译....
Why does using IPage
as an interface type parameter not compile....
public class AboutPageAdminViewModel
: PageAdminViewModel<AboutPage>
, IPageAdminViewModel<IPage> // ERROR HERE - I realise this declaration is not required, just indicating where the error is (not)
{
}
....当使用具体类 AboutPage
吗?
....when using the concrete class AboutPage
does?
public class AboutPageAdminViewModel
: PageAdminViewModel<AboutPage>
, IPageAdminViewModel<AboutPage> // NO ERROR - I realise this declaration is not required, just indicating where the error is (not)
{
}
基本上,我不明白为什么返回类型 IEnumerable< IPage>
与<$ c的返回类型不匹配$ c> IEnumerable< AboutPage> 。
Essentially, I don't understand why the return type of IEnumerable<IPage>
does not match the return type of IEnumerable<AboutPage>
.
我想创建一个方法,它需要 IPageAdminViewModel< IPage>
作为参数。我想知道如何/如果我可以使 AboutPageAdminViewModel
符合该要求。
I would like to create a method that takes IPageAdminViewModel<IPage>
as an argument. I am wondering how / if I can make AboutPageAdminViewModel
fit that requirement.
推荐答案
捡起Eric的例子:
class Animal {}
class Tiger : Animal {}
interface ICage {
Animal GetAnimal(); }
class TigerCage : ICage {
//Won’t compile
public Tiger GetAnimal() =>
new Tiger(); }
您可以通过实现显式接口成员和强类型方法来解决此问题,其中一种方法委托给另一方以避免代码重复:
You can solve this by implementing both an explicit interface member and a strongly typed method, one of which will delegate to the other to avoid code duplication:
class TigerCage: ICage {
Animal ICage.GetAnimal() => GetAnimal();
public Tiger GetAnimal() => new Tiger(); }
这篇关于通用参数 - 使用具体类型编译,但实现的接口不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!