[英]F#: How do I pattern match a type value?
我有一个采用通用参数的 function,在其中我需要根据参数的类型执行两个函数之一。
member this.Load<'T> _path =
let hhType = typeof<HooHah>
match typeof<'T> with
| hhType -> this.LoadLikeCrazy<'T> _path
| _ -> this.LoadWithPizzaz<'T> _path
.... 其中 LoadLikeCrazy 和 LoadWithPizzaz 都返回一个'T。
VS 告诉我通配符的情况永远不会被执行,因为我显然在编译时得到了泛型的类型,而不是运行时的实际类型。 我该如何 go 关于这个?
在您的代码中,第一个模式匹配规则不会将 typeof<'T> 与 hhType 进行比较。 相反,它将引入一个名为 hhType 的新值。 这就是你收到警告的原因。 我宁愿像这样修改代码。
member this.Load<'T> _path =
match typeof<'T> with
| x when x = typeof<HooHah> -> this.LoadLikeCrazy<'T> _path
| _ -> this.LoadWithPizzaz<'T> _path
_path
是'T
的实例吗? 如果是这样,Talljoe 的解决方案将起作用,否则您将不得不执行以下操作:
member this.Load<'T> _path =
if typeof<'T> = typeof<HooHah> then this.LoadLikeCrazy<'T> _path
else this.LoadWithPizzaz<'T> _path
错误的原因是match
表达式中的hhType
隐藏了hhType
的先前声明。 因此,它只是将匹配表达式的值捕获到新绑定中。 这匹配所有内容,因此您的通配符条件将永远不会被击中。
nyinyithann 所说的是正确的。 我在 F# 中编写了以下代码
let Hello name =
let n = "Sample"
match name with
| n -> 1
| _ -> 0
得到了同样的警告。 使用反射器查看生成了什么代码并找到以下代码(用C#反编译)
public static int Hello<a>(a name)
{
a local = name;
a name = local;
return 1;
}
不知道为什么编译器会这样做:(。任何人都可以描述这种行为吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.