C# 代码将使用情况与异常联系起来
在这种情况下,我对代码契约和例外使用的假设是正确的。您认为用代码契约替换异常合乎逻辑吗(反之亦然)C# 代码将使用情况与异常联系起来,c#,exception-handling,C#,Exception Handling,在这种情况下,我对代码契约和例外使用的假设是正确的。您认为用代码契约替换异常合乎逻辑吗(反之亦然) 代码未测试。只是一个示例场景好吧,假设行绕错了方向(即,在尝试使用它之前测试路径是否为null),那么是的,这是一个有效的先决条件,因此应该是一个代码契约。我可能会选择如下实现: void ReadContent(string path) { Contract.Requires(path!=null); string contentofileasstring = filehelperobj
代码未测试。只是一个示例场景好吧,假设行绕错了方向(即,在尝试使用它之前测试路径是否为null),那么是的,这是一个有效的先决条件,因此应该是一个代码契约。我可能会选择如下实现:
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 ;
}
此代码看起来很奇怪,请使用后检查。请澄清这一点。编辑后,错误有点误导。如果发现文件内容错误(空)怎么办?我希望您阅读我编辑的文章。如何区分可能需要抛出的“有效”代码契约和“无效”代码契约?如果内容为空怎么办?这就是我感兴趣的情况(在使用合同和例外之间)。@Jimmy更新了我的答案,以回答您编辑的问题。
private void ReadContent(string path)
{
Contract.Requires<FileMissingException>(File.Exists(path));
string content = filehelperobj.GetContent(path);
m_xmlobj = content;
}
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;
}
}