我正在使用第三方 API,它相当笨拙地利用 ref 参数来生成输出。就我个人而言,我真的很讨厌这种 API 设计,但这是我现在可以使用的。由于专有代码,我不得不稍微隐藏 API 的数据类型,但这应该与当前的问题无关。
无论如何,在 C# 中,我可以成功地将空引用作为 ref 参数传递,如下所示:
IDataType tl = null;
bool success = api.myFunction(ref tl);
但是在 F# 中以下内容将不起作用
let mutable tl : IDataType = null //null reference assignment in F#
let success = api.myFunction(&tl) //& means ref in F#
它返回空引用异常错误。 C# 中不会返回此类错误。
有人以前经历过这种情况吗?我认为这一定是 API 本身的错误,这是相对古老的设计。
**编辑:这应该关闭,我相信答案不在于 F# 代码,而在于 API,因为它已经有许多与此类似的已知错误。
最佳答案
用 C# 快速构建 API 原型(prototype)
namespace API
{
public interface IDataType { void Hi(); }
public class API: IDataType {
public void Hi() { System.Console.WriteLine("Hi!"); }
public bool MyFunction(ref IDataType iface) {
iface = new API();
return true;
}
}
}
然后按照您的方式从 F# 中使用它,同时保持在同一个 CLR 中:
let mutable iface : API.IDataType = null
if API.API().MyFunction(&iface) then iface.Hi()
工作没有任何问题。
因此,事实上,您的问题特定于您给定的 API,与 F# 中的使用形式无关。
关于F# 将空引用传递给 ref 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17724656/