如何在接口中配置代码约定

Fab*_*ber 7 c# interface code-contracts

我无法在课堂上配置代码合同.我已经按照文档和示例,但它不起作用.

我想将Code Contracts条件插入我的界面,这里是我的代码

界面

 [ContractClass(typeof(ArticleBLLContract))]
 public interface IArticleBLL
 {
    int getArticleNSheet(string IdBox);
    IEnumerable<IArticle> getArticleValue(string IdBox, string IdLanguage);
}
Run Code Online (Sandbox Code Playgroud)

合同类

[ContractClassFor(typeof(IArticleBLL))]
public sealed class ArticleBLLContract : IArticleBLL
{
    int IArticleBLL.getArticleNSheet(string IdBox)
    {
        Contract.Requires<ArgumentOutOfRangeException>(!String.IsNullOrEmpty(IdBox),"IdBox has no valid value");                        

        return default(int);
    }

    IEnumerable<Base.Article.IArticle> IArticleBLL.getArticleValue(string IdBox, string IdLanguage)
    {
        Contract.Requires<ArgumentOutOfRangeException>(!String.IsNullOrEmpty(IdBox), "IdBox has no valid value");
        Contract.Requires<ArgumentOutOfRangeException>(!String.IsNullOrEmpty(IdLanguage), "IdLanguagehas no valid value");

        Contract.Ensures(Contract.Result<IEnumerable<Base.Article.IArticle>>() != null, "Return value is out of Range");

        return default(IEnumerable<Base.Article.IArticle>);
    }        
}
Run Code Online (Sandbox Code Playgroud)

申请合同的班级

public class ArticleBLL : IArticleBLL
{

    public int getArticlNSheet(string IdBox)
    {
        try
        {
            return _Dal...
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public IEnumerable<IArticle> getArticleValue(string IdBox, string IdLanguage)
    {
        IEnumerable<IArticle> article = null;

        try
        {
            article = _Dal...

            return article;

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图在这一行插入一个断点

Contract.Requires<ArgumentOutOfRangeException>(!String.IsNullOrEmpty(IdBox),"IdBox has no valid value");  
Run Code Online (Sandbox Code Playgroud)

但是当我调用方法时它永远不会通过这里这是我的项目配置 代码合同配置

有什么不对?

谢谢!

Dam*_*ver 3

根据迄今为止的评论完全重写

我创建了一个类库项目,并将接口及其契约类放入其中。我已将其设置为“标准合同要求”、运行时预检查和后检查以及构建合同参考程序集(我为调试和发布设置了相同的选项)。

然后,我得到了一个控制台应用程序,其中有一个实现接口的类,并设置了“标准合同要求”、运行时预检查和后检查(同样,在调试和发布之间设置相同)。

在调试或发布模式下运行它,ArgumentOutOfRangeException当尝试调用getArticleNSheet.

除了切换到“标准合同要求”的明显例外之外,上面的内容与您当前的设置不匹配吗?


事实上,我之前就犯了错误。通过“标准合同要求”,我实际上可以在调试时在合同类中命中断点。我不确定它是通过什么 Wizardry 来做到这一点的 - 因为它实际上并没有运行该类中的代码 - 正如您可以将合约类中的方法重写为以下事实所证明的那样:

    int IArticleBLL.getArticleNSheet(string IdBox)
    {
        Contract.Requires<ArgumentOutOfRangeException>(!String.IsNullOrEmpty(IdBox), "IdBox has no valid value");

        throw new NotImplementedException();
    }
Run Code Online (Sandbox Code Playgroud)

您可以在该行上放置一个断点Contract.Requires,并且它似乎击中了它(在有关文件不匹配的警告之后,可能是由于重写器所致)。但假设您传递了一个非空字符串,它不会抛出NotImplementedException.