【发布时间】:2013-08-04 18:21:51
【问题描述】:
我写了这段代码
type Test =
| Age of int
| Name of string;;
let x = Age(10);;
if (x.GetType() = typeof<Test>) then printfn "true" else printfn "false";;
代码打印错误。但这让我感到困惑,因为类型 Test 不是 Age 吗?
另外,有没有更好的方法来比较 F# 中的类型,.GetType() = typeof<> 很长。我尝试了:?,但我认为这是用于类型转换而不是比较类型。
【问题讨论】:
-
if (x.GetType() = typeof
) then printfn "true" else printfn "false";;打印错误。 -
> if (x.GetType() :? Test) then printfn "true" else printfn "false";; if (x.GetType() :? Test) then printfn "true" else printfn "false";; ----^^^^^^^^^^^^^^^^^^ 标准输入(52,5):错误 FS0193:类型约束不匹配。 Test 类型与 System.Type 类型不兼容 'Test' 类型与'System.Type' 类型不兼容
-
你看
x.GetType()的结果了吗?这样做。 -
将 x 与 | 匹配:?测试->真| _ -> 假的;;标准输入(59,3):错误 FS0016:“测试”类型没有任何适当的子类型,不能用作类型测试或运行时强制的来源。
-
x.GetType();;验证它:System.Type = FSI_0031+Test+Age 类型为 Test+Age。嗯...现在如何比较和测试它的年龄或名称?
标签: f# f#-interactive f#-3.0