参数类型“A”不能分配给“B”类型?

时间:2014-03-06 16:48:56

标签: c# .net .net-4.5

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

示例接口:

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

1 个答案:

答案 0 :(得分:4)

您尝试将ISomeService的实例(源自IAppService<SomeEntity,ISomeEntitySpecification>)传递给期望IAppService<T, IBaseSpecification<T>>的构造函数。

这两者之间没有等级关系:

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

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

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