我试图理解当我传递给我的基本构造函数的接口实现正确的接口时为什么会得到此异常。

接口示例:

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的构造函数参数。我不知道为什么。

最佳答案

您正在尝试将源自ISomeServiceIAppService<SomeEntity,ISomeEntitySpecification>实例传递给需要IAppService<T, IBaseSpecification<T>>的构造函数。

两者之间没有层次关系:


IAppService<SomeEntity,ISomeEntitySpecification>
IAppService<T, IBaseSpecification<T>>


因为泛型类型参数是不变的。
 由于没有关系,因此您不能将其作为参数传递给构造函数。就像将整数传递给需要字符串的方法一样。

您正在寻找协方差。看一下这个:Covariance and Contravariance FAQ

10-05 17:40