[英]System.InvalidCastException: Specified cast is not valid when trying to use Reflection in F#
I am trying to construct a record type in F#.我正在尝试在 F# 中构造一个记录类型。 But the following code is giving
System.InvalidCastException
.但是下面的代码给出了
System.InvalidCastException
。 I am new to F# and having a difficult time understanding as to why this isn't working.我是 F# 的新手,很难理解为什么这不起作用。 A detailed explanation would be much appreciated.
详细的解释将不胜感激。
open System
open Microsoft.FSharp.Reflection
type Employee = {
Id: Guid
Name: string
Phone: string
BadgeId: string
Designation: string
}
let values =
[
"bc07e94c-b376-45a2-928b-508b888802c9"
"A"
"B"
"C"
"D"
]
|> Seq.ofList
let creator = FSharpValue.PreComputeRecordConstructor(typeof<Employee>, System.Reflection.BindingFlags.Public)
let x =
(
creator [|
values
|> Seq.map (fun y -> y)
|]
) :?> Employee
printfn "%A" x
There are two issues with your code.您的代码有两个问题。 First, your record expects a value of type
Guid
, but you are giving it a guid as a string.首先,您的记录需要一个
Guid
类型的值,但您给它一个 guid 作为字符串。 You can fix this by boxing everyting in your values
list:你可以通过在你的
values
列表中装箱来解决这个问题:
let values =
[
box (Guid("bc07e94c-b376-45a2-928b-508b888802c9"))
box "A"
box "B"
box "C"
box "D"
]
The second issue is that you call creator
with an array containing a sequence as an argument (there is an extra wrapping).第二个问题是您使用包含序列作为参数的数组调用
creator
(有一个额外的包装)。 You need to give it array containing the values:你需要给它包含值的数组:
let emp = creator (Array.ofSeq values) :?> Employee
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.