[英]F# Generic Function
in piping to/from net objects 在往/从净对象的管道中
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. 然后将序列化的Json键/值对通过管道传递到jsonDeserialize中。 It works well.
它运作良好。 My next question is can I genericize the call to JsonConvert.DeserializeObject?
我的下一个问题是我可以泛化对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
给定一个序列化的JSON字符串,我想
let jsDeser =
jsonSerialized
|> jsonDeserialize Dictionary<string, string>
or something like it, in idiomatic F# 或类似的东西,在惯用的F#中
In F#, type arguments are specified and passed in angle brackets: 在F#中,类型参数被指定并在尖括号中传递:
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. 注意:您必须在
JsonConvert.DeserializeObject
上指定通用参数,因为它具有非通用重载,如果您未指定任何内容,则会选择该重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.