gpt4 book ai didi

f# - 无法在 HttpMethod 上进行模式匹配

转载 作者:行者123 更新时间:2023-12-04 18:36:24 25 4
gpt4 key购买 nike

这不会编译。为什么?错误消息令人困惑,为什么模式中不存在该属性?

match System.Net.Http.HttpMethod.Post with
| System.Net.Http.HttpMethod.Post -> "post"
| _ -> "other"

enter image description here

最佳答案

如果您查看 F# reference documentation on pattern matching ,您会看到可以匹配的第一种模式是常量模式,描述为“任何数字、字符或字符串文字、枚举常量或定义的文字标识符”。这些都是编译时常量,因此编译器可以安全地将其编译为已编译 IL 代码中的单个值。然而,System.Net.HttpMethod.Post不是枚举值,它是 HttpMethod 类的静态属性。无法将属性安全地编译为常量值,因为在访问该属性时,相关类可以执行任何操作(包括副作用)。

这就是为什么您不能针对 System.Net.HttpMethod.Post 进行模式匹配的原因:它不是编译时常量。相反,您必须执行以下操作:

match System.Net.Http.HttpMethod.Post with
| method when method = System.Net.Http.HttpMethod.Post -> "post"
| _ -> "other"

这是合法的 F# 语法,可以编译。是的,有点尴尬,但这是 F# 编译器规则与 .Net 库的设计方式交集的结果。

关于f# - 无法在 HttpMethod 上进行模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55211881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com