gpt4 book ai didi

c# - 带有 F# 的 ServiceStack.Redis 不存储数据。但是 C# 中几乎相同的代码都可以工作

转载 作者:IT王子 更新时间:2023-10-29 05:56:35 25 4
gpt4 key购买 nike

今晚我要玩 F# 和 Redis。我正在使用 ServiceStack.redis 连接到在本地主机上运行的 MSOpenTech redis。出于测试目的,我试图使用如下代码将比特币的价格保存到 redis 中:

let redis = new RedisClient("localhost")
redis.FlushAll()

let redisBitstamp = redis.As<BitstampLast>()
let last = {Id = redisBitstamp.GetNextSequence(); Timestamp = 1386459953; Value=714.33M}
redisBitstamp.Store(last)

let allValues = redisBitstamp.GetAll()
allValues.PrintDump()

不幸的是,PrintDump 的结果是:

[
{
__type: "Program+BitstampLast, RedisSave",
Id: 0,
Timestamp: 0,
Value: 0
}
]

出于测试目的,我在同一个 Redis 实例上用 C# 运行了几乎相同的代码:

class BitstampLast
{
public Int64 Id { get; set; }
public int Timestamp { get; set; }
public decimal Value { get; set; }
}

class Program
{
static void Main(string[] args)
{
var redis = new RedisClient("localhost");
redis.FlushAll();

var redisBitstamp = redis.As<BitstampLast>();
var last = new BitstampLast() {Id = redisBitstamp.GetNextSequence(), Timestamp = 1386459953, Value=714.33M};
redisBitstamp.Store(last);

var allValues = redisBitstamp.GetAll();
allValues.PrintDump();

}
}

结果...

[
{
__type: "CSharpRedis.BitstampLast, CSharpRedis",
Id: 1,
Timestamp: 1386459953,
Value: 714.33
}
]

那么,我错过了什么?为什么它在 C# 中有效,而在 F# 中无效?

编辑:BitstampLast 是这样定义的:

type BitstampLast = {Id:int64; Timestamp:int; Value:decimal}

这是错误的,因为它应该是:

type BitstampLast = {mutable Id:int64; mutable Timestamp:int; mutable Value:decimal}

现在可以了。那么接下来的问题 - 为什么它应该是可变的? Redis 是否以某种方式弄乱了这个对象?

最佳答案

许多 ServiceStack 的库(例如序列化、自动映射等)都在具有默认构造函数和可写属性的 POCO 上运行,而 F# 不可变记录默认情况下没有这些属性。

在 F# 中创建 POCO 的最佳方法是使用 CLIMutable 属性对其进行修饰 F# 3.0 Language Feature它为所有可在 C# 代码中访问的属性创建一个具有公共(public) getter 和 setter 的 POCO 类型,但在 F# 中仍表现为不可变类型,例如:

[<CLIMutable>] 
type BitstampLast = { Id:int64; Timestamp:int; Value:decimal }

关于c# - 带有 F# 的 ServiceStack.Redis 不存储数据。但是 C# 中几乎相同的代码都可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20449186/

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