更改不可变对象 F# [英] Changing an immutable object F#

查看:22
本文介绍了更改不可变对象 F#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这个标题是错误的,但不能创建一个抽象地反映我想要实现的目标的标题.

I think the title of this is wrong but can't create a title that reflects, in the abstract, what I want to achieve.

我正在编写一个函数,该函数调用服务并将数据作为 JSON 字符串检索.该函数使用 JSON 类型提供程序解析字符串.在某些条件下,我想修改该 JSON 对象的属性,然后返回修改后对象的字符串.因此,如果呼叫的响应是

I am writing a function which calls a service and retrieves data as a JSON string. The function parses the string with a JSON type provider. Under certain conditions I want to amend properties on that JSON object and then return the string of the amended object. So if the response from the call was

{"property1" : "value1","property2" : "value2", "property3": "value3" }

我想将 property3 更改为新值,然后返回 JSON 字符串.

I want to change property3 to a new value and then return the JSON string.

如果 JsonProvider 是可变的,这将是一个练习:

If the JsonProvider was mutable this would be an exercise like:

type JsonResponse = 
        JsonProvider<""" {"property1" : "value1", 
                          "property2" : "value2",
                          "property3": "value3" } """>

let jsonResponse = JsonResponse.Parse(response)
jsonResponse.Property3 <- "new value"
jsonResponse.ToString()

但是,这不起作用,因为无法设置该属性.我正在尝试确定解决此问题的最佳方法.我很高兴根据原始响应初始化一个新对象,但修改了参数,但我不确定是否有简单的方法来实现这一点.

However, this does not work as the property cannot be set. I am trying to ascertain the best way to resolve this. I am quite happy to initialise a new object based on the original response but with amended parameters but I am not sure if there is an easy way to achieve this.

作为参考,JSON 对象比给出的平面示例要复杂得多,并且包含很深的层次结构.

For reference, the JSON object is much more involved than the flat example given and contains a deep hierarchy.

推荐答案

是的,您需要创建一个新对象,更改所需的位,其余部分使用现有对象的值.不久前,我们为 XML 和 JSON 类型提供程序添加了编写 API.您会注意到表示 JSON 的类型具有构造函数.您可以在 此链接 的底部看到正在使用的示例

Yes, you would need to create a new object, changing the bits you want and using the existing object's values for the rest. We added write APIs for both the XML and JSON type providers a while back. You will notice the types representing your JSON have constructors on them. You can see an example of this in use at the bottom of this link

这篇关于更改不可变对象 F#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆