如何在PowerShell中调用C#编写的泛型方法?
PowerShell调用C#泛型方法的正确方式
问题场景
我用C#创建了一个DLL,其中包含带类型约束的泛型方法TypeName<T>(),代码如下:
public class ClassTest { public string TypeName<T>() where T : FlaUI.Core.AutomationElements.AutomationElement { return typeof(T).FullName; } }
该方法约束T必须是FlaUI.Core.AutomationElements.AutomationElement的派生类型。尝试在PowerShell中调用时执行失败,调用代码如下:
add-type -path C:\Users\unknow\source\repos\AutomationDLL\AutomationDLL\bin\Debug\My.dll add-type -path C:\Users\unknow\source\repos\AutomationDLL\AutomationDLL\bin\Debug\FlaUI.Core.dll add-type -path C:\Users\unknow\source\repos\AutomationDLL\AutomationDLL\bin\Debug\FlaUI.UIA3.dll $instance = new-object ClassTest $instance.TypeName[[FlaUI.Core.AutomationElements.Button]]();
报错信息:
On line:7 character:59 + $instance.TypeName[[FlaUI.Core.AutomationElements.Button]](); + ~ Unexpected token '(' in expression or statement. On line:7 character:60 + $instance.TypeName[[FlaUI.Core.AutomationElements.Button]](); +~ An expression was expected after '('. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken
解决方案
PowerShell不支持C#风格的泛型方法调用语法,需使用以下两种方式之一:
方式一:PowerShell 5.0+简化语法
直接通过-GenericTypeArguments参数指定泛型类型:
$instance.TypeName -GenericTypeArguments [FlaUI.Core.AutomationElements.Button]
方式二:反射调用(兼容所有PowerShell版本)
通过反射获取泛型方法定义,生成具体类型的方法后调用:
# 获取ClassTest类型中的TypeName泛型方法定义 $genericMethod = [ClassTest].GetMethod('TypeName') # 创建针对Button类型的具体泛型方法 $specificMethod = $genericMethod.MakeGenericMethod([FlaUI.Core.AutomationElements.Button]) # 调用方法,$instance为类实例,$null表示无方法参数 $specificMethod.Invoke($instance, $null)
内容的提问来源于stack exchange,提问作者sysOut
相关产品推荐
相关产品推荐

