在C#中,我可以这样做:
var castValue = inputValue as Type1
在F#中,我可以执行以下操作:
let staticValue = inputValue :> Type1
let dynamicValue = inputValue :?> Type1
但是它们都不能等同于C#的关键字as
。
我想我需要为F#中的等价物做一个匹配表达式
match inputValue with
| :? Type1 as type1Value -> type1Value
| _ -> null
这是正确的吗?
发布于 2010-03-02 17:35:32
据我所知,F#没有任何与C# as
等价的内置运算符,因此您需要编写一些更复杂的表达式。对于使用match
的代码,您也可以使用if
,因为运算符:?
的使用方式与C#中的is
相同:
let res = if (inputValue :? Type1) then inputValue :?> Type1 else null
当然,您可以编写一个函数来封装此行为(通过编写一个简单的泛型函数,该函数接受一个Object
并将其强制转换为指定的泛型类型参数):
let castAs<'T when 'T : null> (o:obj) =
match o with
| :? 'T as res -> res
| _ -> null
该实现返回null
,因此它要求类型参数将null
作为适当的值(或者,您可以使用Unchecked.defaultof<'T>
,它相当于C#中的default(T)
)。现在,您只需编写:
let res = castAs<Type1>(inputValue)
发布于 2014-08-11 20:54:07
我会使用主动模式。下面是我使用的方法:
let (|As|_|) (p:'T) : 'U option =
let p = p :> obj
if p :? 'U then Some (p :?> 'U) else None
下面是As
的用法示例
let handleType x =
match x with
| As (x:int) -> printfn "is integer: %d" x
| As (s:string) -> printfn "is string: %s" s
| _ -> printfn "Is neither integer nor string"
// test 'handleType'
handleType 1
handleType "tahir"
handleType 2.
let stringAsObj = "tahir" :> obj
handleType stringAsObj
发布于 2010-03-02 22:41:41
您可以创建自己的运算符来执行此操作。这实际上与Tomas的示例相同,但显示了一种略有不同的调用方式。下面是一个例子:
let (~~) (x:obj) =
match x with
| :? 't as t -> t //'
| _ -> null
let o1 = "test"
let o2 = 2
let s1 = (~~o1 : string) // s1 = "test"
let s2 = (~~o2 : string) // s2 = null
https://stackoverflow.com/questions/2361851
复制相似问题