c# - 当使用 Contract.Assert(true) 并且该方法必须返回某些内容时该怎么办?

标签 c# .net-4.0 code-contracts design-by-contract

我有一些代码具有以下逻辑:

//pseudo-code
foreach (element in elementList) {
    if (element is whatever)
        return element;
    }
}

理论上,总有一个元素是whatever,所以这个方法应该没有问题。无论如何,我在方法的末尾放置了一个断言只是为了确定:

//pseudo-code
foreach (element in elementList) {
    if (element is whatever)
        return element;
    }
}

Contract.Assert(false, "Invalid state!");

问题是因为这个方法必须返回一些东西,而编译器不明白这个断言会中断程序的执行。在使用 Contracts 之前,在这种情况下,我曾经抛出一个 Exception,从而解决了问题。你将如何使用 Contract.Assert() 来处理这个问题?在 Contract.Assert() 调用后返回 null 或 default(element_type) 知道它永远不会被调用并关闭编译器?或者还有其他更优雅的方法吗?

谢谢

最佳答案

你可以去

var result = null;
foreach (element in elementList) {
    if (element is whatever)
        result = element;
        break;
    }
}

Contract.Assert(result != null, "Invalid state!");
return result;

它引入了一个中断,但它确实在返回周围看起来更干净。

会更干净

return elementList.Where( e => e is whatever).First();

按照@devoured 指出的那样进行编辑,上面的内容会覆盖整个列表

清洁无处

return elementList.First( e => e is whatever);

结束编辑

如果找不到任何东西,那只会爆炸。

但如果你真的想要断言,它可能是

var results = elementList.Where( e => e is whatever);
Contract.Assert(results.Count() == 1, "Boo");
return results.First();

但这也会迭代整个列表。

关于c# - 当使用 Contract.Assert(true) 并且该方法必须返回某些内容时该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2779091/

相关文章:

c# - 发送 mhtml 电子邮件 - C#

c# - 在 Unity 中使用 Resources.Load 时搜索所有子文件夹

c# - 如何锁定字典?

c# - 我应该使用哪个 .NET 异常来指示外部应用程序失败?

具有生成器模式的 C# 代码契约(Contract) - "Possibly calling a method on a null reference"

c# - Xamarin.Forms Shell 页面中的自定义 TitleView(顶部栏)

asp.net - ASP.NET 4中.skin文件中的Intellisense

c# - 以字节为单位计算 utf-8 字符串大小?

c# - Contract.Requires 不阻止空引用警告(紫色波浪形)

c# - Autofac 和 Contract 类