gpt4 book ai didi

f# - 在 F# 中添加额外的方法作为类型扩展

转载 作者:行者123 更新时间:2023-12-03 17:54:30 25 4
gpt4 key购买 nike

我有一个已经实现的 .Net 库 .Item方法,例如

namespace Library2
type A() =
member m.Item with get(a: string) = printfn "get a string"
member m.Item with get(a: int) = printfn "simple slice"

在使用这个库的代码中,我想添加一个额外的同名方法(因此它是 optional extensions ):
#r @"Library2.dll"
open Library2
type A with
member m.Item with get(a: bool) =
printfn "get a bool"

以下示例的最后一行无法编译:
let a = new A()
a.["good"]
a.[10]
a.[true]

F# doc说:

Extension methods cannot be virtual or abstract methods. They can overload other methods of the same name, but the compiler gives preference to non-extension methods in the case of an ambiguous call.



这意味着我不能扩展 .ToString/.GetHashCode具有相同的类型签名,但在这里我使用了不同的类型签名。为什么不能扩展新方法?

最佳答案

我认为,问题是由扩展方法实现如下(C#)引起的:

public static class MyModule
{
public static void Item(this A a, bool b)
{
// whatever
}
}

编译器正在寻找 .Item(...)方法,在原 Library2.A中找到类,并且无法搜索任何扩展方法。

请注意,如果所有 .Item(...)重载是扩展方法,一切正常:
module Library2 =
type A() =
member m.dummy = ()

open Library2
type A with
member m.Item with get(a: string) = printfn "get a string"
member m.Item with get(a: int) = printfn "simple slice"
member m.Item with get(a: bool) = printfn "get a bool"

关于f# - 在 F# 中添加额外的方法作为类型扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13413678/

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