"A"类型的参数无法赋值给类型"B"?

3
我正在尝试理解,为什么当我传递给基础构造函数的接口实现了正确的接口时,会出现此异常。
示例接口:
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的构造函数参数。我不确定为什么。


SomeEntity是否派生自AppEntity? - Euphoric
@Euphoric,是的,它可以。 - DDiVita
你确定吗?因为那一行只会导致错误。 - Euphoric
你能展示一下 IBaseSpecification<T> 的签名吗? - Evan L
我非常确定...否则,我的服务类也会出现错误。但这并没有发生。 - DDiVita
@EvanL,我更新了问题。 - DDiVita
1个回答

4
您正试图将一个实现了 IAppService<SomeEntity,ISomeEntitySpecification> 接口的 ISomeService 实例传递给一个期望 IAppService<T, IBaseSpecification<T>> 接口的构造函数。但是,这两个接口之间没有层次关系,因为泛型类型参数是不变的。由于不存在任何关系,您不能将其作为参数传递给构造函数。这就像将整数传递给期望字符串的方法一样。您正在寻求协变性,请参阅:《协变性与逆变性 FAQ》

+1 表示解密代码成功,我怀疑是协方差问题,但无法确定接口是否正确! - BradleyDotNET
+1 我一直在处理 ISomeService 的问题,但还没有达到这个点。干得好! - Evan L
3
@LordTakkera 确实,这相当令人困惑。一个建议:我会重新设计它。使用泛型和几个抽象层级很酷,但是对于接下来看到它的下一个人(可能是其他人,也可能是你几个月后)维护或理解这段代码将是一场灾难。 保持简单 - dcastro
1
@dcastro,通常情况下我不需要传入特定的IBaseSpecification实现。我同意,我应该稍微重构一下。在开发时我有点过于抽象了。 - DDiVita

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接