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

我想通过创建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();
    }

}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...