问题
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 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.
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