Reflection 向上投射通过反射创建的F#记录

Reflection 向上投射通过反射创建的F#记录,reflection,f#,record,Reflection,F#,Record,我一直在搞F#和它的反射,试图从F#中动态创建一个记录类型的对象,我让它大部分工作正常(如下所示),但有一件事——我通过反射创建的记录的类型是“obj”,而不是它应该的(“Person”),我似乎无法以任何方式向上转换它 #light type Person = { Name:string; Age:int; } let example = {Name = "Fredrik"; Age = 23;} // example has type Person = {Name = "

我一直在搞F#和它的反射,试图从F#中动态创建一个记录类型的对象,我让它大部分工作正常(如下所示),但有一件事——我通过反射创建的记录的类型是“obj”,而不是它应该的(“Person”),我似乎无法以任何方式向上转换它

#light

type Person = {
    Name:string;
    Age:int;
}

let example = {Name = "Fredrik"; Age = 23;}
// example has type Person = {Name = "Fredrik"; Age = 23;}

let creator = Reflection.FSharpValue.PrecomputeRecordConstructor(example.GetType(), 
               System.Reflection.BindingFlags.Public)

let reflected = creator [| ("thr" :> obj); (23 :> obj) |]
// here reflected will have the type obj = {Name = "thr"; Age = 23;}

// Function that changes the name of a Person record
let changeName (x:Person) (name:string) = 
    { x with Name = name }

// Works with "example" which is has type "Person"
changeName example "Johan"

// But not with "reflected" since it has type "obj"
changeName reflected "Jack" // Error "This expression has type obj but is here used with type Person. "

// But casting reflected to Person doesn't work either
(reflected :> Person) // Type constraint mismatch. The type   obj is not compatible with 
                      // type  Person. The type 'obj' is not compatible with the type 'Person'. 
                      // C:\Users\thr\Documents\Visual Studio 2008\Projects\
                      // Reflection\Reflection\Script.fsx   34  2   Reflection

尝试使用“另一个强制转换”操作符(因为这次是以另一种方式强制转换)


所以changeName(反映为:?>Person)“Jack”

与:?>运算符之间的区别是什么?最好的解释可能在这里:但最基本的是,如果您要从一个类转到其父类(即,任何对象),您都可以使用:>。但是,如果您使用另一种方法:?>…“:>”是一种向上转换,将对象转换为父类型——它总是安全的,并且编译器可以捕获向上转换错误。“:?>”是向下转换,请将对象转换为子体类型--向下转换永远都不安全,因为向下转换错误总是导致运行时异常。