Generics F#:模式如何匹配类型值?
我有一个接受泛型参数的函数,在它里面我需要根据参数的类型执行两个函数中的一个Generics F#:模式如何匹配类型值?,generics,f#,types,pattern-matching,Generics,F#,Types,Pattern Matching,我有一个接受泛型参数的函数,在它里面我需要根据参数的类型执行两个函数中的一个 member this.Load<'T> _path = let hhType = typeof<HooHah> match typeof<'T> with | hhType -> this.LoadLikeCrazy<'T> _path | _ -> this.LoadWithPizzaz<'T>
member this.Load<'T> _path =
let hhType = typeof<HooHah>
match typeof<'T> with
| hhType -> this.LoadLikeCrazy<'T> _path
| _ -> this.LoadWithPizzaz<'T> _path
成员。使用
|hhType->this.LoadLikeCrazy\u路径
。。。。其中LoadLikeCrazy和LoadWithPizzazz都返回一个T
VS告诉我,通配符案例永远不会执行,因为我显然是在编译时获取泛型的类型,而不是在运行时获取实际的类型。我该怎么做?是
\u path
的一个'T
实例吗?如果是这样,Talljoe的解决方案将起作用,否则您必须执行以下操作:
member this.Load<'T> _path =
if typeof<'T> = typeof<HooHah> then this.LoadLikeCrazy<'T> _path
else this.LoadWithPizzaz<'T> _path
member this.Load=typeof then this.LoadLikeCrazy\u路径
错误的原因是
hhType
表达式中的hhType
隐藏了先前的hhType
声明。因此,它只是将匹配表达式的值捕获到一个新绑定中。这将匹配所有内容,因此您的通配符条件将永远不会被命中。在代码中,第一个模式匹配规则不会比较typeof _path=
匹配_路径的类型
|_->this.loadwithpizzazz尼因伊坦提到的是正确的。我用F写了下面的代码# 收到了同样的警告。使用reflector查看生成的代码,并找到以下代码(用C#反编译)
public static int Hello(一个名称)
{
本地=名称;
a名称=本地;
返回1;
}
不确定编译器为什么会这样做:(.有人能描述这种行为吗?您希望您的代码有什么行为?您可以对名称进行模式匹配,即(将名称与匹配),然后提供两种选择,在第一个规则中创建一个新的变量绑定,也称为“名称”,然后返回0。由于您没有指定任何模式或何时保护,第一个规则将始终匹配,这意味着第二个规则是多余的。您到底想实现什么?我已更新了代码。实际上,第一个模式是:n->1…在给出一个值后,尽管看起来“名称”(变量)-在本例中为“n”-在match内部定义有自己的作用域,与match Blocks之前完成的绑定无关。如果可以使用Literal属性获得所需的行为,Chris Smith提供了更多详细信息:@Robert-我认为这不起作用。
typeof
不被视为常量表达式。
member this.Load<'T> _path =
match typeof<'T> with
| x when x = typeof<HooHah> -> this.LoadLikeCrazy<'T> _path
| _ -> this.LoadWithPizzaz<'T> _path
let Hello name =
let n = "Sample"
match name with
| n -> 1
| _ -> 0
public static int Hello<a>(a name)
{
a local = name;
a name = local;
return 1;
}