F#Riddle:如何调用方法的重载?

时间:2010-01-09 23:49:54

标签: c# interop f# methods call

第一部分:从F#中调用F#

假设我们在F#中定义了以下类型:

type MyClass =
    static member Overload1 (x, y) = "Pim"
    static member Overload1 (x : System.Tuple<_, _>) = "Pam"
    static member Overload1 x = "Pum"

您现在在另一个模块中(在另一个文件中)。

如何调用上面显示的三种方法中的每一种?

第二部分:从F#中调用C#

现在,您在C#中定义一个类:

public class MyClass {
    public static string Overload1<a, b>(a x, b y) { return "Pim"; }
    public static string Overload1<a, b>(Tuple<a, b> x) { return "Pam"; }
    public static string Overload1<a>(a x) { return "Pum"; }
}

从F#代码中,如何调用C#中现在定义的三种方法中的每一种?

2 个答案:

答案 0 :(得分:5)

嗯,我不清楚是否可以调用F#“Pam”方法。但剩下的就是这里。

C#:

using System;
namespace CSharp
{
    public class MyClass
    {
        public static string Overload1<a, b>(a x, b y) { return "Pim"; }
        public static string Overload1<a, b>(Tuple<a, b> x) { return "Pam"; }
        public static string Overload1<a>(a x) { return "Pum"; }
    }
}

F#:

namespace FSharp

type MyClass =
    static member Overload1 (x, y) = "Pim"
    static member Overload1 (x : System.Tuple<_, _>) = "Pam"
    static member Overload1 x = "Pum"

namespace DoIt

module Examples =
    let CallFSharp() =
        printfn "%s" <| FSharp.MyClass.Overload1(1,2)   // Pim
        printfn "%s" <| FSharp.MyClass.Overload1((1,2)) // Pum!
        printfn "%s" <| FSharp.MyClass.Overload1(())    // Pum


    let CallCSharp() =
        printfn "%s" <| CSharp.MyClass.Overload1(1,2)             // Pim
        printfn "%s" <| CSharp.MyClass.Overload1<int,int>((1,2))  // Pam
        printfn "%s" <| CSharp.MyClass.Overload1(())              // Pum

    do
        CallFSharp()        
        CallCSharp()        

当然,在实践中,很少会看到IL中将System.Tuple<...>个对象作为参数的方法。

答案 1 :(得分:4)

以下是F#部分的答案:

MyClass.Overload1(1,2)
MyClass.Overload1<_,_>(unbox (box (1,2)) : System.Tuple<int,int>)
MyClass.Overload1 1