如何从C#调用F#类型扩展(静态成员函数)

Ken*_*Ito 5 c# f#

FSharp代码结构如下(我不控制源代码).

namespace FS

[<AbstractClass; Sealed>]
type TestType() = 
    static member IrrelevantFunction() = 
        0

[<AutoOpen>]
module Extensions = 
    type TestType with
        //How do we call this from C#
        static member NeedToCallThis() = 
            0

module Caller = 
    let CallIt() = 
        //F# can call it
        TestType.NeedToCallThis()
Run Code Online (Sandbox Code Playgroud)

C#调用代码如下

public void Caller()
{
    TestType.IrrelevantFunction();

    //We want to call this
    //TestType.NeedToCallThis();

    //Metadata:

    //namespace FS
    //{
    //    [Microsoft.FSharp.Core.AutoOpenAttribute]
    //    [Microsoft.FSharp.Core.CompilationMappingAttribute]
    //    public static class Extensions
    //    {
    //        public static int TestType.NeedToCallThis.Static();
    //    }
    //}

    //None of these compile
    //TestType.NeedToCallThis();
    //Extensions.TestType.NeedToCallThis.Static();
    //Extensions.TestType.NeedToCallThis();
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 7

我不相信该方法可以直接从C#调用而不使用反射,因为编译的方法名称不是C#中的有效方法名称.

使用反射,您可以通过以下方式调用它:

var result = typeof(FS.Extensions).GetMethod("TestType.NeedToCallThis.Static").Invoke(null,null);
Run Code Online (Sandbox Code Playgroud)

  • @KennethIto是的 - 他们真的只是想用于F#.您可以使用`[<Extension>]`来制作C#耗材的扩展方法,但那个方法实际上并不是出于这些目的. (2认同)