我使用的是安装了 2009 年 10 月版 F# CTP 的 Visual Studio 2008。
我正在尝试从我的 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# 项目和 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
最佳答案
它对我有用,我得到“what's up hello”、“System.Object1”、“System.Object1”用于部分、闭包和 closureWrapper 变量。您引用的是好的 FSharp.Core 程序集吗?
关于c# - 从 C# 调用 F# 函数并获取空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1633562/