F#泛型函数 [英] F# Generic Function
问题描述
在从网络对象到管道 >
我了解到我可以做到这一点:
let jsonDeserialize json = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
然后将序列化的Json键/值对通过管道传输到jsonDeserialize中.它运作良好.我的下一个问题是我可以泛化对JsonConvert.DeserializeObject的调用吗?我想使用它,以便可以将具有相同功能的其他类型反序列化.
我尝试了
let jsonDeserialize json mytype : 'a = JsonConvert.DeserializeObject<'a>(json)
,但后来却不知道如何使用它.给定一个序列化的JSON字符串,我想
let jsDeser =
jsonSerialized
|> jsonDeserialize Dictionary<string, string>
或类似的东西,在惯用的F#中
在F#中,指定类型参数并在尖括号中传递:
let jsonSerialize<'mytype> json : 'mytype = JsonConvert.DeserializeObject<'mytype> json
let jsDeser = jsonSerialized |> jsonDeserialize<Dictionary<string, string>>
或者最好不要指定它们,而让编译器从上下文中找出它们:
let jsonSerialize json = JsonConvert.DeserializeObject<'a> json
let jsDeser : Dictionary<string, string> = jsonDeserialize jsonSerialized
注意:您必须在JsonConvert.DeserializeObject
上指定通用参数,因为它具有非通用重载,如果您不指定任何内容,则会选择该重载.
I learned that I could do this:
let jsonDeserialize json = JsonConvert.DeserializeObject<Dictionary<System.String, System.String>>(json)
then pipe serialized Json Key/Value pairs into jsonDeserialize. It works well. My next question is can I genericize the call to JsonConvert.DeserializeObject? I want to use this so that I can deserialize to other types with the same function.
I tried
let jsonDeserialize json mytype : 'a = JsonConvert.DeserializeObject<'a>(json)
but then couldn't figure out how to use it. Given a serialized JSON string I want to
let jsDeser =
jsonSerialized
|> jsonDeserialize Dictionary<string, string>
or something like it, in idiomatic F#
In F#, type arguments are specified and passed in angle brackets:
let jsonSerialize<'mytype> json : 'mytype = JsonConvert.DeserializeObject<'mytype> json
let jsDeser = jsonSerialized |> jsonDeserialize<Dictionary<string, string>>
Or, preferably, one doesn't specify them at all, but lets the compiler figure them out from the context:
let jsonSerialize json = JsonConvert.DeserializeObject<'a> json
let jsDeser : Dictionary<string, string> = jsonDeserialize jsonSerialized
NOTE: you have to specify the generic argument on JsonConvert.DeserializeObject
, because it has a non-generic overload, which will be selected if you don't specify anything.
这篇关于F#泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!