从C#调用时返回记录选项为空 [英] Return record option as null when calling from C#
本文介绍了从C#调用时返回记录选项为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是以往任何时候都可以从F#返回记录选项
值设置为C#作为空值?我想封装在F#组装一些逻辑,并隐藏的尽我所能门面背后是更自然的C#。下面是一些合成的例子:
Is it ever possible to return record option
value from F# to C# as null value? I want to encapsulate some logic in F# assembly, and hide as much as I can behind facade being "more natural to C#". Here's some synthetic example:
type Data = { DataField1: int; DataField2: string }
和代码返回到C#是这样的:
And code to return to C# would look like this:
type SomeFacade() =
let data = Some { DataField1 = 1; DataField2 = "hello" }
member x.GetData() = if Option.isSome data then Option.get data else null
但它不允许使用空值。
But it is not allowed to use null value.
- 我可以尝试使用
[< AllowNullLiteral>]
属性,但它不能在记录类型使用。 - 我可以使用
类
而不是记录$ C因为大部分的工作都应该在F#零件内部做$ C>,但它会更加复杂与它的工作F#中。我喜欢用
与
关键字复制另一个纪录创造价值的记录值的十分便捷的方式。 - 甚至可以使用
数据
为F#组件内记录并将其转换成一些中间类DATACLASS
暴露到C#程序集的时候,但它看起来别扭。
- I could try to use
[<AllowNullLiteral>]
attribute, but it can't be used on record types. - I could use
Class
instead ofRecord
but it would be more complicated to work with it inside F# as most of work are supposed to be done inside the F# part. And I like the extremely convenient way of creating record values by copying another record value usingwith
keyword. - It is even possible to use
Data
as record inside F# assembly and convert it to some intermediate classDataClass
when exposing to C# assemblies, but it looks awkward.
请问有什么解决办法吗? (我不打算使用F#代码中的空值,但我想为空值返回到C#代码)。
Is there any solution? (I'm not going to use null values inside F# code but I would like to return null values to C# code).
推荐答案
对于记录类型,
Operators.Unchecked.defaultof<Data>
是空
(只使用FSI测试)
is null
(just tested using fsi)
这可能是最简单的解决方案。
This is probably the simplest solution
这篇关于从C#调用时返回记录选项为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文