【发布时间】:2020-07-30 18:24:15
【问题描述】:
我想在 F# 中用this interface 创建一个对象:
namespace JWT
{
/// <summary>
/// Provides JSON Serialize and Deserialize. Allows custom serializers used.
/// </summary>
public interface IJsonSerializer
{
/// <summary>
/// Serialize an object to JSON string
/// </summary>
/// <param name="obj">object</param>
/// <returns>JSON string</returns>
string Serialize(object obj);
/// <summary>
/// Deserialize a JSON string to typed object.
/// </summary>
/// <typeparam name="T">type of object</typeparam>
/// <param name="json">JSON string</param>
/// <returns>Strongly-typed object</returns>
T Deserialize<T>(string json);
}
}
我尝试过使用对象表达式,但通用的 Deserialize 方法让我感到困惑:
let serializer =
{
new JWT.IJsonSerializer
with
member this.Serialize (o : obj) =
failwith "Not implemented"
member this.Deserialize (json : string) =
let decoded : Result<'t, string> =
Decode.fromString payloadDecoder json
match decoded with
| Result.Ok (o : 't) ->
o
| Result.Error error ->
failwith error
}
错误是:
此代码不够通用。类型变量 'a 无法泛化,因为它会超出其范围
我该如何实施?
$ dotnet --version
3.1.300
【问题讨论】:
-
Decode.fromString 的签名是什么?
-
Decode.fromString来自Thoth.Jsonstring -> Decoder<'t> -> Result<'t, string> -
奇怪,这在我的环境中不会发生,我使用的是 F# Core 4.7.2,你的是什么?