如何将对象转换为元组?

时间:2015-02-04 07:50:17

标签: f# f#-3.0

我有一个名为value的变量,它是一个对象,现在我知道该值包含两个类型的元组(我不知道哪些类型)。

注意:我知道该值仅在运行时才是元组。

如何将value {object}转换为value {tuple('A,'B)}?

这是我尝试做的方式

type TdlType=
    |TdlBoolean=0
    |TdlInteger=1
    |TdlTag=2
    |Tdldouble=3
    |TdlString=4
    |TdlDecimal=5
    |TdlChar=6
    |TdlTuple=7
and Tdl(_value,_name:string,_valueType:TdlType)=
    let value:obj=_value
    let name:string=_name
    let valueType:TdlType= _valueType
    member this.valueAsTuple: Option<'A*'B>=if valueType<>TdlType.TdlTuple then 
                                               None 
                                            else 
                                               match value with
                                               |(x,y)->Some((x,y)) //The Error is Here
                                               |_->None

但我对此代码有错误:此表达式被指示为类型为obj但此处的类型为“A *”B

1 个答案:

答案 0 :(得分:1)

这是否符合您的要求?

open System

type TdlType =
| TdlBoolean = 0
| TdlInteger = 1
| TdlTag = 2
| Tdldouble = 3
| TdlString = 4
| TdlDecimal = 5
| TdlChar = 6
| TdlTuple = 7
and Tdl(value : obj, name : string, valueType : TdlType) =
    member this.GetValueAsTuple<'a, 'b> () =
        if valueType <> TdlType.TdlTuple then 
            None 
        else 
            match value with
            | :? Tuple<'a, 'b> as t -> Some (t.Item1, t.Item2)
            | _ -> None

样本FSI输出:

> let x = Tdl("Foo", "Foo", TdlType.TdlString);;

val x : Tdl

> x.GetValueAsTuple<string, string>();;
val it : (string * string) option = None
> let y = Tdl(("Foo", 42), "Foo", TdlType.TdlTuple);;

val y : Tdl

> y.GetValueAsTuple<string, int>();;
val it : (string * int) option = Some ("Foo", 42)

作为一般说明,除非您与某些弱类型的外部系统进行交互,并且这是您尝试将数据从该系统转移到F#代码库中,否则这不是特别惯用的F#代码。

你真的想做什么?这是什么动机?