You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Add-Type使用的C#版本是多少?如何查看其编译器版本?

查看PowerShell Add-Type使用的C#编译器版本及适配方案

一、查看当前PowerShell使用的C#编译器版本

方法1:通过编译代码获取编译器版本

运行以下PowerShell命令,编译并执行一段检测代码:

Add-Type -TypeDefinition @"
using System;
using Microsoft.CSharp;

public class CompilerVersionChecker
{
    public static void Main()
    {
        var provider = new CSharpCodeProvider();
        var compilerAssemblyVersion = provider.GetType().Assembly.GetName().Version;
        Console.WriteLine($"C#编译器程序集版本: {compilerAssemblyVersion}");
        Console.WriteLine(".NET运行时版本: {0}", Environment.Version);
    }
}
"@ -OutputAssembly CompilerVersionChecker.exe
.\CompilerVersionChecker.exe
# 清理临时生成的程序集
Remove-Item CompilerVersionChecker.exe -ErrorAction SilentlyContinue

这段代码通过CSharpCodeProvider获取其程序集版本,该版本与C#编译器版本直接关联,结合.NET运行时版本可以快速对应到具体的C#语言版本。

方法2:直接查找csc.exe版本

如果系统中存在独立的csc.exe,可以直接查询其版本:

$cscPath = (Get-Command csc.exe -ErrorAction SilentlyContinue).Source
if ($cscPath) {
    Write-Host "csc.exe版本: $( (Get-Item $cscPath).VersionInfo.ProductVersion )"
} else {
    Write-Host "未找到独立csc.exe,PowerShell可能使用内置编译器服务"
}

二、编译器版本与C#语言版本对应关系

根据你拥有的VS版本,对应关系如下:

  • VS 2010 → C# 4.0(对应.NET Framework 4.0)
  • VS 2012 → C# 5.0(对应.NET Framework 4.5)
  • VS 2015 → C# 6.0(对应.NET Framework 4.6/.NET Core 1.0)
  • VS 2017 → C# 7.0-7.3(对应.NET Framework 4.7+/.NET Core 2.x)
  • VS 2019 → C# 8.0-9.0(对应.NET Core 3.x/.NET 5)
  • VS 2022 → C# 10.0-12.0(对应.NET 6-8)

三、适配旧编译器的排查方法

  1. 本地模拟编译:拿到目标机器的编译器版本后,使用对应的VS版本创建项目,将代码放入编译,即可复现“功能不支持”的具体错误,针对性修改代码。
  2. 强制指定语言版本:在本地PowerShell中可以通过-CompilerOptions参数强制指定C#语言版本,模拟旧编译器行为:
# 示例:强制使用C# 5.0编译
Add-Type -TypeDefinition $yourCode -Language CSharp -CompilerOptions "/langversion:5"

内容的提问来源于stack exchange,提问作者cup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:32:38