2

我需要使用 PowerShell 来使用 Google 协议缓冲区。尚未找到特定于语言的转换器,并且使用 protobuf-net (C#) 来生成 .cs 代码和后来的 .dll 文件。

所有找到的方法都涉及 New-Object 构造,但在 protobuf-net.dll 中定义了公共静态类 Serializer,因此无法创建对象(类实例)-> 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 方法来解决该问题?

4

2 回答 2

1

这是由于 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)
于 2016-12-21T03:26:49.160 回答
0

我不知道您要问什么,但这里有一些先行者,在 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 SampleClass
于 2012-11-20T08:51:24.177 回答