Ale*_*lex 2 f# types type-systems coercion
在 F# 中,我有一个返回 System.Linq.Expression 实例的函数:
and System.Object with
member this.ToExpression() =
match this with
| :? System.Int32 -> Expression.Constant(this) :> Expression
| :? System.Boolean -> Expression.Constant(this) :> Expression
| :? Tml.Runtime.Seq as s -> s.ToExpression()
| _ -> failwith "bad expression"
Run Code Online (Sandbox Code Playgroud)
如果我省略对返回值的类型强制,F# 会将函数的返回类型推断为 ConstantExpression。我的第一个想法是将返回类型明确标记为:#Expression,但这不起作用。有没有更优雅的方法来做到这一点,而不涉及手动将返回类型转换为最通用的类型?
谢谢。
编辑:感谢大家的回答。我将采用显式返回类型 + 向上转换的场景。
以下是您可能更喜欢的几种方式:
open System.Linq.Expressions
type System.Object with
member this.ToExpression() : Expression = // explicit
match this with
| :? System.Int32 -> upcast Expression.Constant(this) // upcast
| :? System.Boolean -> Expression.Constant(this) :> _ // _
| _ -> failwith "bad expression"
Run Code Online (Sandbox Code Playgroud)
通过在member
声明中明确说明返回类型,您可以在正文中推断它,例如通过_
“请为我推断此类型”或使用upcast
运算符来推断要从约束向上转换的类型。
归档时间: |
|
查看次数: |
1582 次 |
最近记录: |