2010-10-23 76 views
3

我需要指定,我的成員屬性將在C#中返回類似dynamic?的內容。在F#中可以使用動態數據類型嗎?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 

此代碼無法編譯,因爲返回類型從文本案例中確定爲string option。 F#中的關鍵字dynamic未知。有任何想法嗎?

+0

你可以'box'但,很可能這是一個設計缺陷。 – 2010-10-23 20:00:59

回答

2

儘量使這個數據類型:

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

,或者使用System.Object類型:

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 

來獲取值:

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