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

VS 2022自定义代码分析器无生效问题求助

自定义Roslyn代码分析器无效果问题排查

我按照微软官方教程步骤,在Visual Studio 2022中创建了自定义代码分析器解决方案,未修改默认模板生成的代码,但在VSIX实例的简易控制台应用中运行该分析器时无任何效果。根据教程描述,任何包含小写字母的标记应显示波浪下划线,但实际并未出现。

诊断分析器代码

namespace TestAnalyzer
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class TestAnalyzerAnalyzer : DiagnosticAnalyzer
    {
        public const string DiagnosticId = "TestAnalyzer";

        // You can change these strings in the Resources.resx file. If you do not want your analyzer to be localize-able, you can use regular strings for Title and MessageFormat.
        // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/Localizing%20Analyzers.md for more on localization
        private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.AnalyzerTitle), Resources.ResourceManager, typeof(Resources));
        private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.AnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
        private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.AnalyzerDescription), Resources.ResourceManager, typeof(Resources));
        private const string Category = "Naming";

        private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }

        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();

            // TODO: Consider registering other actions that act on syntax instead of or in addition to symbols
            // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/Analyzer%20Actions%20Semantics.md for more information
            context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);
        }

        private static void AnalyzeSymbol(SymbolAnalysisContext context)
        {
            // TODO: Replace the following code with your own analysis, generating Diagnostic objects for any issues you find
            var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;

            // Find just those named type symbols with names containing lowercase letters.
            if (namedTypeSymbol.Name.ToCharArray().Any(char.IsLower))
            {
                // For all such symbols, produce a diagnostic.
                var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name);

                context.ReportDiagnostic(diagnostic);
            }
        }
    }
}

VSIX控制台应用代码

namespace ConsoleCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            const String wordtocheck1 = "racecar";
            const String wordtocheck2 = "racetrack";

            Console.WriteLine($"{wordtocheck1} {(ispalindrome(wordtocheck1) ? "is" : "is not")} a palindrome");
            Console.WriteLine($"{wordtocheck2} {(ispalindrome(wordtocheck2) ? "is" : "is not")} a palindrome");

            Console.ReadLine();
        }
        protected static Boolean ispalindrome(String word)
        {
            for(Int32 i = 0; i < (word.Length / 2); i++)
            {
                if (word[i] != word[(word.Length - 1) - i])
                    return false;
            }

            return true;
        }
    }
}

排查及解决要点

  • 确认VSIX部署配置:检查VSIX项目的source.extension.vsixmanifest,在Assets标签页中确保已将分析器项目添加为"Microsoft.VisualStudio.Analyzer"类型的资产,源选择当前解决方案中的分析器项目。
  • 检查分析器启用状态:在VSIX实验实例中,进入工具 > 选项 > 文本编辑器 > C# > 代码分析 > 常规,勾选"启用基于Roslyn的代码分析";再进入代码分析 > 规则集,确认TestAnalyzer规则处于启用状态。
  • 验证项目引用:查看控制台应用项目的"分析器"节点,确认自定义分析器已被正确引用;若未显示,可手动右键项目 > 添加 > 分析器 > 浏览选择分析器的DLL文件。
  • 手动触发分析:右键控制台项目 > 分析 > 分析并修复代码问题,强制触发分析流程,查看是否生成诊断信息。
  • 核对分析器逻辑:当前分析器仅检查SymbolKind.NamedType(类、结构体等命名类型),而示例中的Program类名全大写,不会触发规则。可测试添加一个含小写字母的类(如class myTestClass),验证是否显示警告波浪线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:44:58