本文介绍了从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>] 属性,但它不能在记录类型使用。
- 我可以使用类而不是记录,但它会更加复杂与它的工作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 of Record 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 using with keyword.
- It is even possible to use Data as record inside F# assembly and convert it to some intermediate class DataClass 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#调用时返回记录选项为空
发布评论