1
void ReadContent(string path)
{
  Contract.Requires(path!=null);
  string contentofileasstring = filehelperobj.GetContent(path);
   if(String.IsNullOrEmpty(contentofileasstring ))
  {
    throw new FileContentException(path + "No content found");
  }
  m_xmlobj = contentofileasstring ;
}

在这种情况下,我对使用代码合同和异常的假设是否正确。您认为用代码合同替换异常是否合乎逻辑(反之亦然)?

代码未测试。只是一个示例场景

4

2 回答 2

1

好吧,假设您的线路错误(即,在尝试使用它之前测试 null 的路径)那么是的,它是一个有效的前提条件,因此应该是一个代码合同。

于 2012-04-27T15:53:35.177 回答
1

我可能会选择如下所示的实现:

private void ReadContent(string path)
{
    Contract.Requires<FileMissingException>(File.Exists(path));
    string content = filehelperobj.GetContent(path);
    m_xmlobj = content;
}

发布编辑

因为它是您要验证的内容,所以我会Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));filehelperobj.GetContent(string)方法中放置一个。然后,如果正在读取的内容为 null 或为空,我会抛出异常。例如

public string GetContent(string path)
{
    Contract.Requires<FileMissingException>(File.Exists(path));
    Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));

    using(var reader = new StreamReader(File.OpenRead(path)))
    {
        var content = reader.ReadToEnd();

        if(String.IsNullOrEmpty(content))
            throw new FileContentException("No content found at file: " + path);

        return content;
    }
}
于 2012-04-27T15:56:40.490 回答