从C#调用时返回记录选项为空

编程入门 行业动态 更新时间:2024-10-20 16:38:13
本文介绍了从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#调用时返回记录选项为空

本文发布于:2023-10-24 14:05:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524131.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   选项

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!