ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-10-29 21:07:51  阅读:230  来源: 互联网

标签:net-4-5 c net


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

接口示例:

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

解决方法:

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

两者之间没有层次关系:

> IAppService< SomeEntity,ISomeEntitySpecification>和
> IAppService< T,IBaseSpecification< T&gt ;,
因为泛型类型参数是不变的.
 由于没有关系,因此您不能将其作为参数传递给构造函数.就像将整数传递给需要字符串的方法一样.

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

标签:net-4-5,c,net
来源: https://codeday.me/bug/20191029/1962771.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有