Skip to main content
 首页 » 编程设计

c#之未使用 ContractClassFor 应用代码契约(Contract)

2024年02月13日15exmyth

这个让我难住了。我在契约(Contract)适用的方法是接口(interface)实现的场景中使用代码契约(Contract)。因此,我使用抽象的 ContractClassFor 方法来定义契约(Contract)要求。这适用于其中一个实现类(它恰好与接口(interface)在同一个项目中),但契约(Contract)永远不会应用于第二个实现(它在一个单独的项目中)。这两个项目具有相同的代码契约(Contract)设置(标准契约(Contract)要求;完整的运行时契约(Contract)检查)。这是代码中的场景:

namespace First.Interfaces { 
    [ContractClass(typeof(ContractForIMyClass))] 
    public interface IMyClass { 
        void MyMethod(int id); 
    } 
 
    [ContractClassFor(typeof(IMyClass))] 
    public abstract class ContractForIMyClass : IMyClass 
    { 
        void MyMethod(int id) { 
            Contract.Requires<ArgumentException>(id != 0); 
        } 
    } 
} 
 
namespace First { 
    public class MyClass : IMyClass { 
        public void MyMethod(int id) { 
            //contract is applied here 
        } 
    } 
} 
 
namespace Second { 
    public class MyTestClass : IMyClass { 
        public void MyMethod(int id) { 
            //contract is not applied 
        } 
    } 
} 

任何想法都非常感谢。

请您参考如下方法:

你需要做两件事才能让它工作:

  1. 为包含接口(interface)的程序集构建契约引用程序集。
  2. 在构建包含第二个类的项目时使用该契约(Contract)引用程序集。

这两个选项都可以从 Visual Studio 中各个项目的属性页面中的代码契约(Contract)部分进行控制。 (如果您在单个解决方案中使用标准项目引用,那么一旦您修复了 #1,您可能不必为 #2 做任何事情。)