How to call F# type extensions (static member functions) from C#

拈花ヽ惹草 提交于 2020-01-14 10:07:05

问题


FSharp code is structured as following (I'm not in control of the source).

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()

C# calling code is as follows

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();
}

回答1:


I don't believe the method can be called directly from C# without using reflection, as the compiled method name is not a valid method name in C#.

Using reflection, you can call it via:

var result = typeof(FS.Extensions).GetMethod("TestType.NeedToCallThis.Static").Invoke(null,null);


来源:https://stackoverflow.com/questions/36296516/how-to-call-f-type-extensions-static-member-functions-from-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!