10

我正在使用 StackExchange.Redis 访问 Redis 实例。

我有以下工作 C# 代码:

public static void Demo()
{
    ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("xxx.redis.cache.windows.net,ssl=true,password=xxx");

    IDatabase cache = connection.GetDatabase();

    cache.StringSet("key1", "value");
}

这是我希望等效的 F# 代码:

let Demo() =
   let cx = ConnectionMultiplexer.Connect @"xxx.redis.cache.windows.net,ssl=true,password=xxx"
   let cache = cx.GetDatabase()
   cache.StringSet("key1", "value") |> ignore

但是,这不会编译 - “方法 StringSet 没有重载匹配”。StringSet 方法需要 RedisKey 和 RedisValue 类型的参数,并且 C# 中似乎有一些编译器魔法将调用代码中的字符串转换为 RedisKey 和 RedisValue。F# 中似乎不存在这种魔法。有没有办法达到相同的结果?

4

1 回答 1

13

这是工作代码,非常感谢@Daniel:

open StackExchange.Redis
open System.Collections.Generic

let inline (~~) (x:^a) : ^b = ((^a or ^b) : (static member op_Implicit: ^a -> ^b) x)

let Demo() =
   let cx = ConnectionMultiplexer.Connect @"xxx.redis.cache.windows.net,ssl=true,password==xxx"
   let cache = cx.GetDatabase()

   // Setting a value - need to convert both arguments:
   cache.StringSet(~~"key1", ~~"value") |> ignore

   // Getting a value - need to convert argument and result:
   cache.StringGet(~~"key1") |> (~~) |> printfn "%s"
于 2014-12-03T15:17:09.913 回答