代码约定使用,但有例外

  • 本文关键字:约定 代码 c# exception
  • 更新时间 :
  • 英文 :

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 ;
}

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

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

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

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

帖子编辑

由于这是您要验证的内容,因此我会在filehelperobj.GetContent(string)方法中放入一个Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<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;
    }
}

好吧,假设你的行是错误的(即,在尝试使用它之前测试路径的null),那么是的,这是一个有效的先决条件,因此应该是一个代码契约。