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

如何在使用.NET Compiler SDK编译时启用Implicit Usings特性?

如何在Roslyn编译中启用C# 10的Implicit Usings特性?

C# 10的「Implicit Usings」特性允许代码省略标准命名空间的using语句,但直接使用Roslyn编译代码时,默认不会启用该特性,导致标准命名空间下的符号(如Console)无法被解析,示例代码如下:

using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

var sourceText = "class C{" +
    "public void M(){" +
    " Console.Write(123);" +
    "}}";
var syntaxTree = CSharpSyntaxTree.ParseText(sourceText);

var coreReferences =
    ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"))
    .Split(Path.PathSeparator)
    .Select(p => MetadataReference.CreateFromFile(p));
var compilation = CSharpCompilation.Create("MyAnalysis")
    .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
    .AddReferences(coreReferences)
    .AddSyntaxTrees(syntaxTree);

var diagnostics = compilation.GetDiagnostics();
Debug.Assert(diagnostics.Length == 0);
// 实际会报错:error CS0103: The name 'Console' does not exist in the current context

解决步骤

要启用Implicit Usings特性,需要修改CSharpCompilationOptions的配置:

  1. 指定语言版本为C# 10或更高,因为该特性是C# 10引入的;
  2. 启用隐式using,并配置默认的标准命名空间集合。

修改后的编译配置代码如下:

var compilation = CSharpCompilation.Create("MyAnalysis")
    .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
        // 指定C# 10及以上版本
        .WithLanguageVersion(LanguageVersion.CSharp10)
        // 启用默认的隐式命名空间
        .WithImplicitUsings(ImplicitUsingsValues.Default))
    .AddReferences(coreReferences)
    .AddSyntaxTrees(syntaxTree);

说明

  • WithLanguageVersion(LanguageVersion.CSharp10)确保编译器支持Implicit Usings特性;
  • WithImplicitUsings(ImplicitUsingsValues.Default)会自动引入.NET默认的标准命名空间(包括System),因此Console无需手动添加using System即可被解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:44:54