Yin*_*Zhu 5 extension-methods f#
我有一个已经实现了.Item方法的.Net库,例如
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"
Run Code Online (Sandbox Code Playgroud)
在使用此库的代码中,我想添加一个同名的额外方法(因此它是optional extensions):
#r @"Library2.dll"
open Library2
type A with
member m.Item with get(a: bool) =
printfn "get a bool"
Run Code Online (Sandbox Code Playgroud)
以下示例的最后一行无法编译:
let a = new A()
a.["good"]
a.[10]
a.[true]
Run Code Online (Sandbox Code Playgroud)
在F#DOC说:
扩展方法不能是虚方法或抽象方法.它们可以重载其他同名的方法,但是在调用模糊的情况下,编译器会优先使用非扩展方法.
这意味着我无法.ToString/.GetHashCode使用相同类型的签名进行扩展,但在这里我使用了不同类型的签名.为什么新方法无法扩展?
我认为,问题是由扩展方法的实现如下(C#)引起的:
public static class MyModule
{
public static void Item(this A a, bool b)
{
// whatever
}
}
Run Code Online (Sandbox Code Playgroud)
编译器正在寻找.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"
Run Code Online (Sandbox Code Playgroud)