gpt4 book ai didi

f# - 如何使用 F# 实现此通用 C# 接口(interface)?

转载 作者:行者123 更新时间:2023-12-05 07:03:31 25 4
gpt4 key购买 nike

我想用 this interface 创建一个对象在 F# 中:

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
}

错误是:

This code is not sufficiently generic. The type variable 'a could not be generalized because it would escape its scope

我该如何实现?


$ dotnet --version
3.1.300

最佳答案

我们可以通过注释成员来处理这个错误。这样类型系统将有足够的信息来完全辨别正在发生的事情。

如果我稍微调整一下你的代码,我就能让它编译:

open Thoth.Json

type IJsonSerializer =
abstract member Serialize : o:obj -> string
abstract member Deserialize<'a> : json:string -> 'a

type Json () =
let payloadDecoder : Decoder<'a> =
fun _ -> failwith "not impl."

interface IJsonSerializer with
member this.Serialize (o : obj) : string =
failwith "not impl."

member this.Deserialize<'a> (json : string) : 'a =
match Decode.fromString payloadDecoder json with
| Ok (o : 'a) -> o
| Error error -> failwith error

通过对 Deserialize 成员进行完整注解,现在应该可以满足类型系统了。

有几点需要注意:

  • 我包含了一个 F# 版本的 IJsonSerializer 接口(interface),这样我的代码就可以编译了。虽然这对您的最终结果来说不是必需的。
  • 我为 payloadDecoder 添加了一个 stub ,因为您没有将它包含在您的问题中。因此,即使这段代码可以编译,它实际上也不会工作。

关于f# - 如何使用 F# 实现此通用 C# 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63179147/

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