简体   繁体   English

避免在接口合同类中重复

[英]Avoiding repetition in Interface contract classes

We want to use code contracts on our interfaces. 我们想在接口上使用代码协定。 We have a large interface hierarchy, leading to an awful lot of duplication in the contract classes. 我们的接口层次结构很大,导致合同类中的重复很多。

We have an interface IX which (through inheriting from other interfaces) has around 50 methods. 我们有一个接口IX (通过从其他接口继承)有大约50种方法。 There are several interfaces that derive from IX . 有几个来自IX接口。 Interface IY inherits from IX , adding only a couple of methods. 接口IY继承自IX ,仅添加了两种方法。 If I want to add a contract class for IY , I need to reference all 50+ methods. 如果要为IY添加合同类,则需要引用所有50多种方法。 Worse, if later on I decide to modify IX , I have to change all the contract classes for all interfaces inheriting from IX . 更糟糕的是,如果以后我决定修改IX ,则必须更改从IX继承的所有接口的所有协定类。 This discourages developers from making changes. 这不鼓励开发人员进行更改。

Is there a way of avoiding this duplication? 有办法避免这种重复吗?

I don't believe this is possible, no. 我不认为这是可能的,不。 You can't derive one interface contract class from another, and interface contracts classes can't have any base class other than System.Object. 您不能从另一个接口合约类派生一个接口合约类,并且接口合约类除System.Object外不能具有任何基类。 So I think you're stuck. 所以我认为你被困住了。 Your best way forwards would probably involve some kind of code generation tool, or lots of copy-and-pasting. 最好的前进方式可能涉及某种代码生成工具,或大量复制粘贴操作。

I have this same problem with some code I have been writing although not quite on the same scale. 我在写一些代码时也遇到了同样的问题,尽管规模不尽相同。 My solution has been to use the IDE/ReSharper to just add the NotImplementedException stubs for new methods or write them as abstract override . 我的解决方案是使用IDE / ReSharper仅为新方法添加NotImplementedException存根,或将它们写为abstract override All contracts defined in the base class should be in stone at that point as the CC tools will yell at you if you attempt to add Contract.Requires to them in the contract class for IY for example. 此时基类中定义的所有合同都应该是一成不变的,因为如果您尝试添加Contract.Requires ,CC工具会大吼大叫。例如,在IY的合同类中对它们有要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM