在可移植类库中使用F# JsonProvider失败

3

我正在尝试使用JsonProvider,但是当我调用它的函数时出现以下错误:

System.TypeInitializationException was unhandled
Message: An unhandled exception of type 'System.TypeInitializationException' occurred in PortableLibrary1.dll
Additional information: The type initializer for '<StartupCode$PortableLibrary1>.$PortableLibrary1' threw an exception.

我有一个基本的控制台应用程序,如下所示:

module Pinit =
   open FSharp.Data

   type JsonT = JsonProvider<"""..\myFile.json""">
   let doc = JsonT.Load("""..\nyFile.json""")
   let result = doc.GeneratedAt

[<EntryPoint>]
let main argv = 
    printfn "%A" Pinit.doc.GeneratedAt
    0 

如果在ConsoleApplication中运行,则一切正常。 如果创建如下的F#可移植类库:

module Pinit =
   open FSharp.Data

   type JsonT = JsonProvider<"""..\myFile.json""">
   let doc = JsonT.Load("""..\nyFile.json""")
   let result = doc.GeneratedAt

创建另一个控制台应用程序并引用该可移植类库,并按以下方式调用代码:
open PortableLibrary1

[<EntryPoint>]
let main argv = 
    printfn "%A" Pinit.result
    0 

当我运行程序时,它会生成上述异常:

我怀疑这是由于 FSharp.Core 的版本问题,想知道是否有哪里出了问题,或者是否有解决方法?

版本信息:

-- ConsoleApplication --
FSharp.Core = 4.3.1.0

-- PortableClassLibrary --
FSharp.Core = 3.3.1.0
FSharp.Data = NuGet Version: 2.0.0

Pinit.result 是什么? - Søren Debois
我已经更新了我的问题,将Pinit.result分配为JsonProvider的结果。这只是一个赋值的结果,在这种情况下,它恰好是一个System.DateTime。 - Andy B
1个回答

2

let绑定被编译成静态成员,在.NET中,当您在静态初始化程序中遇到异常时,真正的异常会被掩盖。

如果您将其转换为函数调用,即通过更改为let result() = doc.GeneratedAtprintfn "%A" (Pinit.result()),您将获得真正的异常:

Only web locations are supported

便携式档案不支持访问文件系统。因此,在PCL内部,您可以使用Web URL或从嵌入式资源手动加载。请参见此处的示例:https://github.com/ovatsus/Apps/blob/master/Trains/Stations.fs#L65。或者您可以在控制台项目中使用File.ReadAllText加载文件,并将其传递给PCL。

这是使用便携式配置文件(Legacy)项目进行的,该项目是Profile 47(和FSharp.Core 2.3.6.0)。然后我还测试了一个便携式档案项目,它是Profile 7(和FSharp.Core 3.3),并注意到它无法正常工作,而是出现了以下异常:

Method not found: 'FSharp.Data.Runtime.JsonValueOptionAndPath FSharp.Data.Runtime.JsonRuntime.TryGetPropertyUnpackedWithPath(FSharp.Data.Runtime.IJsonDocument, System.String)'.

我创建了一个GitHub问题来跟踪此事:https://github.com/fsharp/FSharp.Data/issues/521


谢谢。我现在已经切换到使用嵌入式资源,但不幸的是我正在使用Profile 7,所以我遇到了你上面提到的方法未找到异常。 - Andy B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接