gpt4 book ai didi

F# 多属性 CLIMutable DataContract

转载 作者:可可西里 更新时间:2023-11-01 11:13:32 26 4
gpt4 key购买 nike

在将 ServiceStack.Redis 与 f# 结合使用时,我遇到了组合属性的问题。也许我在考虑这个错误,但现在我希望我的类型被序列化为 JSON,但也可以传递给 ServicvStack。 f# types 的问题是没有默认构造函数,而且添加到我的 Redis 实例的数据是空的,记录在那里,但其中没有任何数据。

这是一个例子:

open System
open ServiceStack.Redis

[<CLIMutable>]
[<DataContract>]
type Car = {
[<field: DataMember(Name="ID")>]
ID : int64
[<field: DataMember(Name="Make")>]
Make : string
[<field: DataMember(Name="Model")>]
Model : string
}
let redisCar = redis.As<Car>()

let redisAddCar car : Car =
let redisCar = redis.As<Car>()
redisCar.Store({ car with ID = redisCar.GetNextSequence() })

let car1 = redisAddCar { ID = 0L; Make = "Honda"; Model = "Accord LX" }
let car2 = redisAddCar { ID = 0L; Make = "Honda"; Model = "Accord EX" }
let car3 = redisAddCar { ID = 0L; Make = "Honda"; Model = "Accord SX" }

let cars = redisCar.GetAll()
cars |> Seq.iter (fun car -> printfn "ID: %i, Make: %s, Model: %s" car.ID car.Make car.Model)

这将打印出:

ID: 0, Make: , Model:
ID: 0, Make: , Model:
ID: 0, Make: , Model:

但是,如果我将类型更改为:

[<CLIMutable>]
[<DataContract>]
type Car = {
[<field: DataMember(Name="ID")>]
mutable ID : int64
[<field: DataMember(Name="Make")>]
mutable Make : string
[<field: DataMember(Name="Model")>]
mutable Model : string
}

然后会打印出来:

ID: 1, Make: Honda, Model: Accord LX
ID: 2, Make: Honda, Model: Accord EX
ID: 3, Make: Honda, Model: Accord SX

为什么我必须向每个属性添加可变的,即使它是通过属性定义的?我希望它不可变,因为我不希望状态发生变化。也许我想太多了,应该只创建一个新类型并将不可变类型转换为可变类型,以便它可以与 ServiceStack.Redis 一起使用?

最佳答案

当从 F# 代码使用记录时,

CLIMutable 属性不会影响记录行为。对于 F# 代码,它仍然是不可变记录。看这里:http://blogs.msdn.com/b/fsharpteam/archive/2012/07/19/more-about-fsharp-3.0-language-features.aspx

"In F# 3.0, we’ve added CLIMutableAttribute. If you attach this attribute to an F# record type, then the F# compiler emits a default constructor and property setters into the generated IL for this type (though those features are not exposed to F# code)."

关于F# 多属性 CLIMutable DataContract,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28845241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com