Return record option as null when calling from C#

别说谁变了你拦得住时间么 提交于 2019-12-10 09:33:16

问题


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 }

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.

  • 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.

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).


回答1:


For record types,

Operators.Unchecked.defaultof<Data>

is null (just tested using fsi)

This is probably the simplest solution



来源:https://stackoverflow.com/questions/9355859/return-record-option-as-null-when-calling-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!