如何通过类的名称将unbox对象转换为实际对象

Rav*_*are 3 reflection f# f#-data

我想通过使用实际对象的名称将对象拆箱到其实际类型.

type Employee = {
    Id:int
    Name:string
}
let defEmployee = {
    Id=1
    Name="Mahi"
}

//actual object
let actualObject = defEmployee
let empAsObject = actualObject :> obj // type with casted in base class
let actualObject = unbox(empAsObject) //here I am trying to unboxing but not 
   able to do it.
Run Code Online (Sandbox Code Playgroud)

当我有实际类型的对象运行时但我只有类型/对象的名称时,我可以这样做

The*_*Fox 5

unbox函数将obj转换为类型'T.要做到这一点,它需要知道要转换为哪种类型.通常,这可以通过来自周围上下文的类型推断来解决,但在这种情况下,编译器没有该信息.因此,您需要提供类型.一种方法是将type参数显式传递给unbox:

let actualEmployee = unbox<Employee> empAsObject
Run Code Online (Sandbox Code Playgroud)

请注意,unbox操作不安全.如果值实际上不是,它将抛出运行时异常Employee.这是您在决定超出类型系统和框值时所采取的风险.