受歧视的工会中的类型之间的转换

Vit*_*liy 4 f# type-conversion discriminated-union

我有一个函数,可以返回不同的类型,我使用歧视联合.我需要的是将有区别的联合中的一种类型转换为另一种类型.还有一些类型可以转换为所有其他类型(String),但是某些类型只能转换为String(MyCustomType)

为此,我已将成员方法ConvertTo添加到ResultType:

type MyTypes = 
   | Boolean       = 1
   | Integer       = 2
   | Decimal       = 3
   | Double        = 4
   | String        = 5
   | MyCustomType  = 6

type ResultType = 
   | Boolean of bool
   | Integer of int
   | Decimal of decimal
   | Double of double
   | String of string
   | MyCustomType of MyCustomType

   with 
     member this.ConvertTo(newType: MyTypes) = 
       match this with 
       | ResultType.Boolean(value) -> 
           match newType with 
           | MyTypes.Boolean -> 
              this
           | MyTypes.Integer -> 
              ResultType.Integer(if value then 1 else 0)
          ...
       | ResultType.MyCustomType(value) -> 
           match newType with 
           | MyTypes.MyCustomType -> 
              this
           | MyTypes.String -> 
              ResultType.String(value.ToString()) 
           | _ -> 
              failwithf "Conversion from MyCustomType to %s is not supported" (newType.ToString())
Run Code Online (Sandbox Code Playgroud)

我不喜欢这样的构造,因为如果我添加更多类型,这需要我做很多更改:MyTypes,ResultType以及ConvertTo成员函数中的几个地方.

任何人都可以为这种类型转换提出更好的解决方案

提前致谢

wme*_*yer 8

通过略微不同的设计,可以利用System.Convert.ChangeType以及有区别的联合的构造函数实际上起作用的事实:

// statically typed wrapper for System.Convert.ChangeType
let conv a : 'T = System.Convert.ChangeType(a, typeof<'T>) :?> 'T

type MyCustomType() = class end

type ResultType = 
  | Boolean of bool
  | Integer of int
  | Decimal of decimal
  | Double of double
  | String of string
  | MyCustomType of MyCustomType
  with
    member this.ConvertTo (newType:'T->ResultType) =
      match this with
      | Boolean b -> newType( conv b )
      | Integer i -> newType( conv i )
      | Decimal d -> newType( conv d )
      | Double d -> newType( conv d )
      | String s -> newType( conv s )
      | MyCustomType m ->
         if typeof<'T> <> typeof<string> then
            raise (new System.InvalidCastException("MyCustomType can only be converted to String"))
         else
            String (m.ToString())

let i = Integer 42

let b = i.ConvertTo Boolean
printfn "%A" b

let d = i.ConvertTo Decimal
printfn "%A" d

let d2 = i.ConvertTo Double
printfn "%A" d2

let s = i.ConvertTo String
printfn "%A" s

//let mi = i.ConvertTo MyCustomType  // throws InvalidCastException

let m = MyCustomType (new MyCustomType())
let sm = m.ConvertTo String
printfn "%A" sm

//let im = m.ConvertTo Integer // throws InvalidCastException
Run Code Online (Sandbox Code Playgroud)

编辑:一旦你添加更多自定义类型,这将没有多大帮助.

也许你应该让你的自定义类型实现IConvertible.然后,您可以从中删除特殊案例代码ConvertTo并完全依赖System.Convert.ChangeType.

ToObject每当添加新的自定义类型时,您仍然需要扩展每个自定义类型的实现.这是否真的比中央ConvertTo功能更好是值得商榷的.