查看“︁卫语句”︁的源代码
←
卫语句
跳转到导航
跳转到搜索
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
在[[计算机程序设计]]中,'''卫'''(guard)是[[布尔逻辑|布尔表达式]],其结果必须为真,程序才能执行下去。'''卫语句'''('''guard code'''或'''guard clause''')用于检查[[先决条件]]。卫语句的用途,例如: *引用(reference)使用前检查是否为空引用; *{{tsl|en|dispose pattern|处置模式}}使用一个布尔域,使得释放资源操作成为[[幂等]]运算,即多次释放资源等效于只释放一次。 ==概述== 卫语句可用于[[子进程]]的'''提前退出'''(early exit),这是[[结构化程序设计]]的一种常见偏离,可删除一层嵌套使得代码更扁平:<ref name="beck">{{cite book |title=Smalltalk Best Practice Patterns, |url=https://archive.org/details/smalltalkbestpra0000beck |first=Kent |last=Beck |authorlink=Kent Beck |year=1997 |section=Guard Clause |pages=[https://archive.org/details/smalltalkbestpra0000beck/page/178 178]–179}}</ref> 把<code>if guard { ... }</code>替代为:<code>if not guard: return; ...</code>. 在[[APL語言|APL]]、[[Haskell]]、[[Clean (编程语言)|Clean]]、[[Erlang]]、[[occam]]、{{tsl|en|Promela}}、[[OCaml]]、[[Swift_(程式語言)|Swift]]<ref>{{Cite web | url = http://nshipster.com/guard-and-defer/ | title = guard & defer | last = Cook | first = Nate | website = NSHipster | access-date = 2016-02-26 | archive-date = 2020-11-25 | archive-url = https://web.archive.org/web/20201125200149/https://nshipster.com/guard-and-defer/ | dead-url = no }}</ref>与[[Scala]]程序设计语言中,这一术语有特殊含义。 [[Mathematica]]中,卫被称为约束(constraints)。 [[形式化方法]]的一种语言,[[守卫命令语言]]中,卫是基础概念。 在增强的[[模式匹配]]中,卫语句用于跳过一些即使结构匹配的模式。 [[条件表达式|条件语句]]中的布尔表达式也符合卫的定义,虽然被称作“条件”。 下述Haskell语言的例子,卫出现在每对"|"与"="之间: <syntaxhighlight lang="haskell"> f x | x > 0 = 1 | otherwise = 0 </syntaxhighlight> 这类似于如下的数学表示的"if"与"otherwise" 子句就是卫语句: <math> f(x) = \left\{ \begin{matrix} 1 & \mbox{if } x>0 \\ 0 & \mbox{otherwise} \end{matrix} \right. </math> 如果有多个平行的卫语句,则按照自顶向下顺序,第一个通过的分支被选择。 == 例子 == <syntaxhighlight lang="csharp"> public string Foo(string username) { if (username == null) { throw new ArgumentNullException(nameof(username)); } // Rest of the method code follows here... } </syntaxhighlight> ==参考文献== {{Reflist}} ==外部链接== * [http://foldoc.org/guard Guard] {{Wayback|url=http://foldoc.org/guard |date=20201130205119 }} in ''Free On-Line Dictionary of Computing - FOLDOC'', Denis Howe (editor). * ''The Haskell 98 Report'', chapter [http://haskell.org/onlinereport/exps.html 3 Expressions]{{Wayback|url=http://haskell.org/onlinereport/exps.html |date=20201111163830 }}. * ''The Mathematica Book,'' section [https://web.archive.org/web/20050408114902/http://documents.wolfram.com/mathematica/book/section-2.3.5 2.3.5 Putting Constraints on Patterns] * ''The Glorious Glasgow Haskell Compilation System User's Guide'', Version 6.4, section [https://web.archive.org/web/20051129140339/http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#pattern-guards 7.3.2. Pattern guards] [[Category:條件結構]]
该页面使用的模板:
Template:Cite book
(
查看源代码
)
Template:Cite web
(
查看源代码
)
Template:Reflist
(
查看源代码
)
Template:Tsl
(
查看源代码
)
Template:Wayback
(
查看源代码
)
返回
卫语句
。
导航菜单
个人工具
登录
命名空间
页面
讨论
不转换
查看
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
MediaWiki帮助
特殊页面
工具
链入页面
相关更改
页面信息