Upcasting F # запись, созданная с помощью отражения

StackOverflow https://stackoverflow.com/questions/637989

  •  10-07-2019
  •  | 
  •  

Вопрос

Я возился с F # и его Reflection, пытаясь динамически создать объект типа Record из F #, у меня большая часть его работала (как вы можете видеть ниже), но одно - запись, которую я создаю с помощью отражения имеет тип " obj " вместо того, который он должен (" Персона "), и я не могу каким-либо образом изменить его.

#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) " Джек "

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top