FSharp 和 Microsoft Office PIA

FSharp and Microsoft Office PIA

我正在使用 FSharp 的 Microsoft Office PIA。当我尝试像这样从 Microsoft Word 获取 SynonymInfo 时:

#r "Office.dll"
#r "Microsoft.Office.Interop.Word.dll"
open Microsoft.Office.Interop.Word

let application = ApplicationClass()
let synonymInfo = application.SynonymInfo("bracket")
let meaningList = synonymInfo.MeaningList :?> string[]

我遇到了这个异常:

System.InvalidCastException: Unable to cast object of type 'System.String[*]' to type 'System.String[]'.

COM 对象的强制转换是否导致此问题?我怎样才能正确投射这个? * 是元组吗?如果这样string[]也不行...

谢谢

Office 互操作 returns 一个数组,其中索引不是从 0 而是(可能)从 1(好旧的 Visual Basic 时代!)这就是 * 在类型中的含义String[*].

您甚至可以从 F# 创建这样的数组:

let array = System.Array.CreateInstance(typeof<int>, [| 10 |], [| 1 |]) 

不幸的是,Int32[*] 是与 Int32[] 不同的类型,因此转换失败:

// System.InvalidCastException: Unable to cast 
// object of type 'System.Int32[*]' to type 'System.Int32[]'.
array :?> int[]

您需要以另一种方式将 1 索引数组中的数据转换为其他结构。在我的例子中 array 的类型实现了非泛型 IEnumerable,所以你应该可以这样写:

array |> Seq.cast<int> |> Array.ofSeq

如果您的值的类型是 obj,您需要先将其转换为接口:

(thing :?> IEnumerable) |> Seq.cast<string> |> Array.ofSeq

您还可以使用类似这样的方式获取包含索引值对的数组:

[| for i in array.GetLowerBound(0) .. array.GetUpperBound(0) ->
     i, array.GetValue(i) :?> int |]