質問
C#によって全然違います:
var castValue = inputValue as Type1
F#,によって全然違います:
let staticValue = inputValue :> Type1
let dynamicValue = inputValue :?> Type1
なのに相当するものC#'sキーワード as
.
思い一致を表現する相当のF#
match inputValue with
| :? Type1 as type1Value -> type1Value
| _ -> null
すが、いかがでしょうか?
解決
私の知る限りでは、F#は、任意の組み込みのC#のas
にオペレータと同等あなたには、いくつかのより複雑な式を記述する必要があるので、必要はありません。オペレータmatch
は、C#でif
と同じように使用することができますので、代わりにあなたのコードを使用:?
に、あなたはまた、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
は、それは、タイプパラメータが適切な値(あるいは、あなたがC#でnull
に相当するUnchecked.defaultof<'T>
を、使用することができる)としてdefault(T)
を有することを必要とします。今、あなただけ書くことができます:
let res = castAs<Type1>(inputValue)
他のヒント
私はアクティブなパターンを使用します。ここでは1つのIの使用は次のとおりです。
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
あなたはこれを行うには、独自の演算子を作成することができます。これはトーマスの例と実質的に同じですが、それを呼び出すために、わずかに異なる方法を示しています。ここでは例があります:
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
私は推測する私はFで同等の一致式を行う必要があります#
match inputValue with | :? Type1 as type1Value -> type1Value | _ -> null
これは正しいですか?
はい、それは正しいです。 (あなた自身の答えは私の意見では答えの残りの部分よりも優れています。)