我试图理解为什么当我传入基础构造函数的接口实现正确的接口时,我得到此异常。
示例接口:
public interface IAppService<T,TSpecification> where T: AppEntity
where TSpecification: IBaseSpecification<T>
{
......
}
//I tried setting both the ISomeEntitySpecification and SomeEntitySpecification implementation
public interface ISomeService: IAppService<SomeEntity,ISomeEntitySpecification>
{
.....
}
public interface ISomeEntitySpecification: IBaseSpecification<SomeEntity>
{
.....
}
public interface IBaseSpecification<T> where T: class
{
....
}
示例实现:
public class SomeEntitySpecification: BaseSpecification<SomeEntity>, ISomeEntitySpecification
{
...
}
public class SomeService: AppService<SomeEntity,SomeEntitySpecification>, ISomeService
{
....
}
示例用法:
public BaseAppController<T>: Controller where T: AppEntity
{
public BaseAppController(IAppService<T, IBaseSpecification<T>>)
{
.....
}
}
//This is where i get the error
public SomeController: BaseAppController<SomeEntity>
{
public SomeController(ISomeService someService):base(someService)
{
.....
}
}
Visual Studio的IDE告诉我someService
无法分配给BaseAppController
的构造函数参数。我不知道为什么。
答案 0 :(得分:4)
您尝试将ISomeService
的实例(源自IAppService<SomeEntity,ISomeEntitySpecification>
)传递给期望IAppService<T, IBaseSpecification<T>>
的构造函数。
这两者之间没有等级关系:
IAppService<SomeEntity,ISomeEntitySpecification>
和IAppService<T, IBaseSpecification<T>>
,因为泛型类型参数是不变。 由于没有关系,因此您无法将其作为参数传递给构造函数。这就像将整数传递给期望字符串的方法一样。
你正在寻找协方差。看看这个:Covariance and Contravariance FAQ