我认为(人为的)实际示例可能有助于阐明差异:
(改编自MoreLinq的Batch扩展)
// 'public facing' method
public int DoSomething(List<string> stuff, object doohickey, int limit) {
// validate user input and report problems externally with exceptions
if(stuff == null) throw new ArgumentNullException("stuff");
if(doohickey == null) throw new ArgumentNullException("doohickey");
if(limit <= 0) throw new ArgumentOutOfRangeException("limit", limit, "Should be > 0");
return DoSomethingImpl(stuff, doohickey, limit);
}
// 'developer only' method
private static int DoSomethingImpl(List<string> stuff, object doohickey, int limit) {
// validate input that should only come from other programming methods
// which we have control over (e.g. we already validated user input in
// the calling method above), so anything using this method shouldn't
// need to report problems externally, and compilation mode can remove
// this "unnecessary" check from production
Debug.Assert(stuff != null);
Debug.Assert(doohickey != null);
Debug.Assert(limit > 0);
/* now do the actual work... */
}
因此,正如Eric Lippert等人所说的那样,您只能断言您期望正确的内容,以防万一您(开发人员)在其他地方不小心使用了它,以便您可以修复代码。当您无法控制或无法预料其中的内容时(例如,对于用户输入),您基本上会抛出异常,从而使任何给它的坏数据都可以适当地响应(例如,用户)。