You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在PowerShell中调用带类型参数的.NET DLL函数遇语法问题

解决PowerShell调用OpenXml泛型Descendants方法的问题

PowerShell不支持C#风格的<>泛型语法,要调用Descendants<T>泛型方法,有以下几种可行方式:

方式1:直接传递类型参数(推荐)

PowerShell中调用泛型方法时,需将泛型类型作为参数传入方法,替代C#的<T>语法:

# 确保引用正确的命名空间,若未导入需写全类型名
$formFields = $mainPart.Document.Body.Descendants([DocumentFormat.OpenXml.Wordprocessing.FormFieldData])

如果提前导入命名空间,可以简化类型名:

using namespace DocumentFormat.OpenXml.Wordprocessing
$formFields = $mainPart.Document.Body.Descendants([FormFieldData])

方式2:先获取所有元素再过滤类型

如果觉得泛型调用麻烦,也可以先获取所有子元素,再用-is运算符过滤指定类型:

$formFields = $mainPart.Document.Body.Descendants() | Where-Object { $_ -is [DocumentFormat.OpenXml.Wordprocessing.FormFieldData] }

这种方式逻辑直观,但性能略低于直接调用泛型方法(元素数量多时差异明显)。

方式3:通过反射调用泛型方法

如果需要更灵活的泛型方法调用(比如动态指定类型),可以用反射获取泛型方法定义后调用:

# 获取Descendants的泛型方法定义
$genericMethod = [DocumentFormat.OpenXml.OpenXmlElement].GetMethod("Descendants").MakeGenericMethod([DocumentFormat.OpenXml.Wordprocessing.FormFieldData])
# 调用方法,第一个参数是实例对象,第二个是方法参数(此处无参数传$null)
$formFields = $genericMethod.Invoke($mainPart.Document.Body, $null)

关键说明

PowerShell中<是重定向运算符,所以不能像C#那样用Descendants<FormFieldData>()的写法,必须用参数传递泛型类型的方式调用泛型方法。

内容的提问来源于stack exchange,提问作者Kevin Rak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 11:48:29