加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 不能同时指定约束类和’类’或’结构’约束

发布时间:2020-12-15 06:26:47 所属栏目:百科 来源:网络整理
导读:我想通过创建IDbSet的定制模拟来解决一个 mocking issue. 定制模拟: public class DbSetMock : IDbSetTenant{ /* hidden all other implemented methods/properties */ public TDerivedEntity CreateTDerivedEntity() where TDerivedEntity : class,Tenant
我想通过创建IDbSet的定制模拟来解决一个 mocking issue.

定制模拟:

public class DbSetMock : IDbSet<Tenant>
{
    /* hidden all other implemented methods/properties */

    public TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : class,Tenant
    {
        throw new NotImplementedException();
    }
}

create方法给出一个构建错误,我没有解释如何解释的线索:

cannot specify both a constraint class and the ‘class’ or ‘struct’ constraint

简单地从约束中删除类导致另一个构建错误(我也不明白:()).

The constraints for type parameter ‘TDerivedEntity’ of method ‘Tests.DAL.Tenants.DbSetMock.Create<TDerivedEntity>()’ must match the constraints for type parameter ‘TDerivedEntity’ of interface method ‘System.Data.Entity.IDbSet<BusinessLayer.DAL.Tenants.Tenant>.Create<TDerivedEntity>()’. Consider using an explicit interface implementation instead.

有人可以帮我成功地建立这个班吗?

解决方法

由于TDerived类型参数被限制为租户,因此添加约束类或结构是多余的.只需删除类约束.

更新:好奇地似乎在这里编译错误之间有冲突.如果你“修复”一个你得到另一个,在无限循环的绝望.幸运的是,第二个错误也给了我们一个办法:你可以使用一个明确的界面实现:

public class DbSetMock : IDbSet<Tenant>
{

    TDerivedEntity IDbSet<Tenant>.Create<TDerivedEntity>()
    {
        throw new NotImplementedException();
    }

}

似乎没有办法实现该方法而不使用显式接口实现.如果您需要它作为该类的公共接口的一部分,我建议创建一个接口实现转发到另一个方法:

public class DbSetMock : IDbSet<Tenant>
{

    TDerivedEntity IDbSet<Tenant>.Create<TDerivedEntity>()
    {
        return Create<TDerivedEntity>();
    }

    public TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : Tenant
    {
        throw new NotImplementedException();
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读