如何将对象转换为元组?

How to convert object to Tuple?

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

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

如何将值 {object} 转换为值 {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

这是否符合您的要求?

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# 代码。

你到底想做什么?这样做的动机是什么?