如何从F#向C#返回空元组? [英] How do you return a null Tuple from f# to c#?
问题描述
我具有此类型正确的C#函数:
I have this type-correct C# function:
static System.Tuple<int,int> f(int n) {
switch (n) {
case 0: return null;
default: return System.Tuple.Create(n,n+1);
}
}
我尝试在F#中重新实现它:
I try to re-implement it in F#:
let f = function
| 0 -> null
| n -> System.Tuple.Create(n, n+1)
类型检查器不同意,
error FS0001: The type '('a * 'b)' does not have 'null' as a proper value.
如何在F#中重新实现原始的C#函数 f
?
How do I re-implement the original C# function f
in F#?
请注意,虽然这看起来像是如何在F#中返回null"(答案:不要,使用Option)的问题,但我们在询问如何从C#消费者从F#返回"中稍有不同."(不能使用Option,下面提供有用的答案).
Note that while this looks like the question "how do I return null in F#" (answer: don’t, use Option) we are asking the slightly different "how do we return null from F# for C# consumers" (can’t use Option, helpful answer below).
推荐答案
如果需要它与C#互操作,则可以使用 Unchecked.Defaultof
像这样:
If you need it to interop with C#, you can use Unchecked.Defaultof
like so:
let f = function
| 0 -> Unchecked.Defaultof<_>
| n -> (n, n + 1)
但是,在F#中强烈建议不要使用空值,并且如果互操作性不是您的主要关注点,那么使用选项会更加自然:
However, using null values is strongly discouraged in F#, and if interoperability is not your main concern, using an option is much more natural:
let f = function
| 0 -> None
| n -> Some (n, n + 1)
这篇关于如何从F#向C#返回空元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!