我正在尝试解决 mocking issue通过创建 IDbSet 的自定义模拟。
自定义模拟:
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
简单地从约束中删除 class
会导致另一个构建错误(我也不明白 :( )。
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
类型参数被限制为 Tenant
,因此添加约束 class
或 struct
是多余的。只需删除 class
约束即可。
更新:奇怪的是,这里的编译器错误之间似乎存在冲突。如果你“修复”了一个,你就会得到另一个,陷入无限的绝望循环。幸运的是,第二个错误也为我们提供了一条出路:您可以使用显式接口(interface)实现:
public class DbSetMock : IDbSet<Tenant>
{
TDerivedEntity IDbSet<Tenant>.Create<TDerivedEntity>()
{
throw new NotImplementedException();
}
}
如果不使用显式接口(interface)实现,似乎无法实现该方法。如果您需要它作为类的公共(public)接口(interface)的一部分,我建议创建接口(interface)实现转发到的另一个方法:
public class DbSetMock : IDbSet<Tenant>
{
TDerivedEntity IDbSet<Tenant>.Create<TDerivedEntity>()
{
return Create<TDerivedEntity>();
}
public TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : Tenant
{
throw new NotImplementedException();
}
}
关于c# - 不能同时指定约束类和 0x104567910 或 'class' 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14418071/