c# - 如何使用 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 来做到这一点。
解决方案
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 }
推荐阅读
- django - 如何在用户配置文件模型中上传图像,同时与 django rest 框架中的用户模型具有一对一的关系?
- spring - Spring Data JPA 投影集合
- react-native - 如何在本机反应中导航到 BottomTabNavigator 内的另一个导航?
- angular - 如何将图像导入打字稿?他说“找不到模块”
- tensorflow - 警告:张量流:提前停止以不可用的度量“val_binary_accuracy”为条件
- react-native - 反应原生获取默认样式道具?
- java - 多态数组类规则(超市程序)
- kotlin - 将 Any 类型的对象转换为类 + 接口的实现
- powershell - 某些 cmdlet 中未定义 PowetShell OutputType
- python - 获取 FileNotFoundError:尝试读取 csv 文件时