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

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

概述我想通过创建IDbSet的定制模拟来解决一个 mocking issue. 定制模拟: public class DbSetMock : IDbSet<Tenant>{ /* hidden all other implemented methods/properties */ public TDerivedEntity Create<TDerivedEntity>() wher 我想通过创建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();    }}
总结

以上是内存溢出为你收集整理的c# – 不能同时指定约束类和’类’或’结构’约束全部内容,希望文章能够帮你解决c# – 不能同时指定约束类和’类’或’结构’约束所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1258173.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存