【问题标题】:What does it mean to upcast a value to the _ wildcard?将值向上转换为 _ 通配符是什么意思?
【发布时间】:2016-11-15 18:10:39
【问题描述】:

在 case 语句末尾实现通配符是什么意思?

采用以下语法:

match imp req with
| Success () -> this.Ok () :> _

是否与以下相同:

| Success () -> this.Ok () :> IHttpActionResult

编写这种语法有什么好处?

这是我的问题的背景:

type PushController (imp) =
    inherit ApiController ()

    member this.Post (portalId : string, req : PushRequestDtr) : IHttpActionResult =
        match imp req with
        | Success () -> this.Ok () :> _
        | Failure (ValidationFailure msg) -> this.BadRequest msg :> _
        | Failure (IntegrationFailure msg) ->
            this.InternalServerError (InvalidOperationException msg) :> _

【问题讨论】:

  • 这不是通配符,您只是让编译器根据您提供的Post 签名为您推断类型转换。
  • 哦...那么推断此签名所需的返回类型是什么?
  • 是的。我对此并不肯定,但| Success () -> this.Ok () :> IHttpActionResult 可能允许您在其余情况下使用_,而签名中没有返回类型。试试看。
  • 不应该 upcast (this.Ok ()) 足够在这里(和其他情况下的相同原则)作为返回类型被指定,也可能更清晰?

标签: f#


【解决方案1】:

运算符:> 对其右侧的表达式指定的类型执行静态向上转换。该运算符的语法是:

:> 表达式

以您为例:

some_value :> IHttpActionResult

这告诉编译器some_value 实际上是一个实现IHttpActionResult 的对象。

但根据 F# 文档:

当您使用向上转换运算符时,编译器会尝试推断 您要从上下文转换为的类型。如果编译器无法 判断目标类型,编译器报错。

https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/casting-and-conversions-%5Bfsharp%5D

因为Post方法可以返回的唯一类型是IHttpActionResult,所以可以让编译器推断。

因此,在这种情况下:

:> _

相当于:

:> IHttpActionResult

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    相关资源
    最近更新 更多