我需要使用PowerShell来使用Google Protocol Buffer。尚未找到特定于语言的转换器,已使用protobuf-net (C#)生成.cs代码,然后生成.dll文件。
所有找到的方法都涉及New-Object构造,但公共静态类序列化程序是在protobuf-net.dll中定义的,因此无法创建对象(类实例) -> New-Object : Constructor not found。找不到类型ProtoBuf.Serializer的适当构造函数。
$memory_stream = New-Object System.IO.MemoryStream
#######
$obj = new-object ControlInterface.EnableGate
$obj.GateId = 2
$obj.Day = 7
#######
$method = [ProtoBuf.Serializer]
$Serialize = $method.GetMethods() | Where-Object {
$_.Name -eq "Serialize" -and
$_.MetadataToken -eq "110665038"
}
$massive = @($memory_stream,$obj)
$closedMethod = $Serialize.MakeGenericMethod([ControlInterface.EnableGate])
$closedMethod.Invoke($method,$massive)当前错误如下:使用"2“参数调用"Invoke”时出现异常:“无法将'System.Management.Automation.PSObject‘类型的对象转换为’System.IO.Stream‘类型。”
有没有可能避免使用C#额外的代码,而只使用PowerShell方法来克服这个问题?
发布于 2016-12-21 11:26:49
这是因为PowerShell将新创建的对象转换为动态PSObject类型,而不是实际的.NET类型。
您所要做的就是对对象变量声明应用强制转换,这样您的问题就会消失。(我花了很长时间才找到答案)
修复您的示例:
[IO.MemoryStream] $memory_stream = New-Object IO.MemoryStream
#######
[ControlInterface.EnableGate] $obj = new-object ControlInterface.EnableGate
$obj.GateId = 2
$obj.Day = 7
#######
$method = [ProtoBuf.Serializer]
$Serialize = $method.GetMethods() | Where-Object {
$_.Name -eq "Serialize" -and
$_.MetadataToken -eq "110665038"
}
$massive = @($memory_stream,$obj)
$closedMethod = $Serialize.MakeGenericMethod([ControlInterface.EnableGate])
$closedMethod.Invoke($method,$massive)发布于 2012-11-20 16:51:24
我不知道你想问什么,但这里有一些指针,在PowerShell中,你可以用::调用静态方法。
例如:
[System.IO.Path]::GetFileName("C:\somefile.jpg")但不管怎么说,如果你想在C#中做这件事,你可以这样做:
$source = @"
public class SampleClass
{
public static int Add(int a, int b)
{
return (a + b);
}
public int Multiply(int a, int b)
{
return (a * b);
}
}
"@
Add-Type $source
$obj = New-Object SampleClasshttps://stackoverflow.com/questions/13424293
复制相似问题