开发者

F# dynamic option

开发者 https://www.devze.com 2023-01-22 05:11 出处:网络
I need to specify, that my member property will return something like dynamic? in C#. Is possible use dynamic data type in F#?

I need to specify, that my member property will return something like dynamic? in C#. Is possible use dynamic data type in F#?

type Data =
    | Text of string
    | Number of string
    | Date of string
    with

    member x.Value
        with get() : dynamic option = 
            match x with
            | Text(value) ->
                if value.Length > 0 then Some(value) else None
            | Number(value) ->
                let (success, number) = Decimal.TryParse value
                if (success) then Some(number) else None
            | Date(value) ->
                let (success, date) = DateTime.TryParse value
                if (success) then Some(date) else None

This code cannot be compiled,开发者_如何学Go because return type is determined as string option from Text case. Keyword dynamic is unknown in F#. Any ideas?


Try to make this datatype:

type ThreeWay = S of string | N of Decimal | D of DateTime

or, use the System.Object type:

open System
type Data =
    | Text of string
    | Number of string
    | Date of string
    with

    member x.Value
        with get() : Object option = 
            match x with
            | Text(value) ->
                if value.Length > 0 then Some(value :> Object) else None
            | Number(value) ->
                let (success, number) = Decimal.TryParse value
                if (success) then Some(number :> Object) else None
            | Date(value) ->
                let (success, date) = DateTime.TryParse value
                if (success) then Some(date :> Object) else None

To get the value:

let d = Number("123")
let v = d.Value
match v with
| Some(x) -> x :?> Decimal // <-- TYPE CAST HERE
0

精彩评论

暂无评论...
验证码 换一张
取 消