从C#调用F#函数并获取空引用异常

时间:2009-10-27 20:48:38

标签: c# f# closures fastfunc

我正在使用Visual Studio 2008和2009年10月安装的F#CTP。

我正试图从我的C#程序中调用一些F#代码。大多数类型的F#函数似乎都有效,但有些函数没有在F#中初始化并抛出NullReferenceExceptions。这样做的是闭包和部分应用的函数,即在C#中作为FastFunc<>出现的东西。类型。

有什么我做错了或忘了,或者这可能是F#或.NET的错误?

以下代码是演示问题。我实际上并没有尝试在真正的应用程序中使用此代码。 同样,在F#中,一切正常。这是一个F#到C#问题

F#:

namespace FS      
module FunctionTypes =

    //these all work in c# as expected
    let Value = "value"

    let OneParam (str:string) = str

    let TwoParam (str:string) (str2:string) = str + " " + str2

    let Lambda =
        fun () -> "lambda"  


    //these functions are null references in C#
    // they do work as expected in F# interactive mode
    let PartialApplication = TwoParam "what's up"

    let Closure = 
        let o = new System.Object()
        fun (i:int) -> o.ToString() + i.ToString()

    let ClosureWrapper (i:int) =
        Closure i  

C#(引用F#project和FSharp.Core)

 //these work as expected:
        var oneParam = FS.FunctionTypes.OneParam("hey");
        var twoParam = FS.FunctionTypes.TwoParam("yeah", "you");
        var lambdaFunction = FS.FunctionTypes.Lambda();
        var value = FS.FunctionTypes.Value;
        //  in the May09 CTP, Value returned null, 
        //      so it must have been fixed in Oct09 CTP



 //these do not work--each throws a NullReferenceException.
        var partial = FS.FunctionTypes.PartialApplication.Invoke("hello");
        var closure = FS.FunctionTypes.Closure.Invoke(1);
        var closureWrapper = FS.FunctionTypes.ClosureWrapper(1);

 //  FS.FunctionTypes.Closure itself is null, 
 //  so is FS.FunctionTypes.PartialAppliction.
 //  FS.FunctionTypes.ClosureWrapper is a regular function, 
 //    but it calls Closure, which is null     

1 个答案:

答案 0 :(得分:2)

它适用于我,我得到“你好了什么”,“System.Object1”,“System.Object1”for partial,closure和closureWrapper vars。您是否引用了良好的FSharp.Core程序集?