2014-12-03 18 views
10

我正在使用StackExchange.Redis來訪問Redis實例。如何從F調用Redis的StringSet()#

我有以下工作的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#中。有沒有達到相同結果的方法?

+0

是否有'RedisKey.op_Implicit'和'RedisValue.op_Implicit'運營商? – Daniel 2014-12-03 15:03:10

+0

@丹尼爾 - 看起來像。如果我瀏覽到清晰,我得到以下.fsi產生: 型RedisKey = ... 靜態成員op_Implicit:關鍵:字符串 - > RedisKey 靜態成員op_Implicit:關鍵:字節[] - > RedisKey 靜態成員op_Implicit :key:RedisKey - > byte [] static member op_Implicit:key:RedisKey - > string – Kit 2014-12-03 15:05:26

+3

然後你需要做'StringSet(RedisKey.op_Implicit「key1」,RedisValue.op_Implicit「value」)''。這些在C#中自動調用,但不是F#。你也可以[定義一個「隱式」操作符](http://stackoverflow.com/a/10720073/162396)。 – Daniel 2014-12-03 15:08:37

回答

11

這裏是工作的代碼,非常感謝@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" 
+0

很多工具我有一個類似的問題 我有一個字符串鍵和值 我希望把它變成和它弄出來的Redis的 讓searchToken = RedisKey.op_Implicit( 「的myKey」 +令牌) 讓resultValue = cache.StringGet(searchToken) 讓redisData = RedisValue.op_Implicit(resultValue) 當我跑,我得到:類型 'RedisValue' 不支持轉換的類型「 「A」 不知道我做錯了。我如何告訴RedisValue.op_Implicit它確實是一個字符串? – 2017-09-07 17:24:00