首页 > 解决方案 > 如何使用 PowerShell 编译带有字符串插值的 C#/VB 代码?

问题描述

我在Windows 10.0.18363.959 和PowerShell 5.1.18362.752

尝试在PowerShell中编译C#VB.NET代码时,如下所示:

$Source = @'
Imports Microsoft.VisualBasic
Imports System

Public NotInheritable Class MainClass

    Public Shared Sub Main()
        Console.WriteLine($"{True}")
    End Sub

End Class
'@ 

$vbType = Add-Type -TypeDefinition $Source `
                   -CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider) `
                   -PassThru `
                   -ReferencedAssemblies "Microsoft.VisualBasic.dll", `
                                         "System.dll" `
                                         | where { $_.IsPublic }

[MainClass]::Main()

$Console = [System.Console]
$Console::WriteLine("Press any key to exit...")
$Console::ReadKey($true)
Exit(0)

我收到编译器错误,因为用于字符串插值的“ $ ”字符:

C:\Users\Administrador\AppData\Local\Temp\oshdpbp1\oshdpbp1.0.vb(12) : >>> Console.WriteLine($"{1}")

我知道我可以改用String.Format()函数,但我想知道是否可以在不修改原始 VB.NET 代码的情况下解决这个问题(当然它可以在Visual Studio上编译)。

请注意,在VB14中添加了字符串插值。也许我错过了如何指定正确的 VB 编译器版本,我不知道如何使用 PowerShell 来做到这一点。

标签: c#.netvb.netpowershell

解决方案


VBCodeProvider有一个带有参数的构造IDictionary函数,允许您指定编译器版本。

这可以工作,但我现在无法测试它:

$provOptions = [System.Collections.Generic.Dictionary[string,string]]::new()
$provOptions['CompilerVersion'] = 'v14.0'

$vbType = Add-Type -TypeDefinition $Source `
                   -CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider $provOptions) `
                   -PassThru `
                   -ReferencedAssemblies "Microsoft.VisualBasic.dll", `
                                         "System.dll" `
                                         | where { $_.IsPublic }

推荐阅读