我在无法修改的外部DLL中具有C#类。库中的两个类定义如下,需要在Powershell脚本中使用。
public class MyCsharpClass<TKey, TValue> : ISomeBaseClass<TKey, TValue>
{
public MyCsharpClass(string path, ISomeBaseTranslator<TKey, TValue> translator)
{
...
}
}
...
...
public class MyByteTranslatorCSharpClass: ISomeBaseTranslator<byte[], byte[]>
{
...
}
我想在Powershell脚本中创建MyCsharpClass的实例,如下所示:
$MyType = [MyCsharpClass[byte[],byte[]]]::new($Path, [MyByteTranslatorCSharpClass]::new())
但是上面的行失败并显示以下错误。我可以在PS ISE命令窗口中输入类型名称,并得到相同的错误。
PS C:\> [MyCsharpClass[byte[],byte[]]]
At line:1 char:30
+ [MyCsharpClass[byte[],byte[]]]
+ ~
Unexpected token ']' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
当我仅将字节类型用作TKey时,向我显示了类的类型信息,但以下行工作正常:
PS C:\> [MyCsharpClass[byte,byte[]]]
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False MyCsharpClass System.Object
似乎我的Key类型的byte []的第一个右括号']'使Powershell混淆了类型定义正在关闭,因此当它在表达式末尾观察到意外的标记']'时,就会引发错误。
我还尝试用System.Collections.Generic.List类型替换byte []类型,该类型现在可以很好地用于声明类型。
PS C:\> MyCsharpClass[System.Collections.Generic.List[System.Byte],System.Collections.Generic.List[System.Byte]]]
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False MyCsharpClass System.Object
但是,这一次构造函数调用失败,同时将MyByteTranslatorCSharpClass的实例作为构造函数中的第二个参数传递(在下一行的末尾)。
$MyType = [MyCsharpClass[System.Collections.Generic.List[System.Byte],System.Collections.Generic.List[System.Byte]]]::new($Path, [MyByteTranslatorCSharpClass]::new())
这给出了'System.Management.Automation.MethodException的异常:无法将参数“ translator”转换为值“ MyByteTranslatorCSharpClass”,对于“ .ctor”,键入“ ISomeBaseTranslator [System.Collections.Generic.List 1[System.Byte],System.Collections.Generic.List
1 [System.Byte] ]”
在这种情况下,请让我知道,如何在Powershell中为TKey和TValue通用参数创建具有byte []类型的MyCsharpClass实例。请注意,我既不能更改DLL端,也无法获取其源代码。
这似乎是类型名称解析错误。
幸运的是,您可以通过使用一对额外的方括号([]
)“限定”类型参数文字来轻松解决此问题:
[MyCsharpClass[[byte[]],[byte[]]]]::new(...)
...或通过直接使用反射构造具体类型:
$myType = [MyCsharpClass`2].MakeGenericType(@([byte[]],[byte[]]))
$myType::new(...)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句