Visual Studio Code中没有C#代码分析。

8

我目前在使用VS Code进行C#开发,因为我认为它比Visual Studio本身更加轻量级,但是似乎没有可用的代码分析工具。这是一个问题,因为我没有得到有关未使用函数的任何警告(但是我可以得到有关未使用本地变量的警告)。

一些示例代码:

namespace MyProject
{
    // No warning for this unused class.
    public class Dog
    {
        private int _age;
        private string _name;

        // No warning for this unused field.
        private string _furColor;

        public Dog(int age, string name)
        {
            // This unused variable generates a warning as expected.
            int unusedVariable = 2;

            _age = age;
            _name = name;
        }

        // No warning for this unused private function.
        private int Age()
        {
            return _age;
        }

        // No warning for this unused public function.
        public string Name()
        {
            return _name;
        }
    }
}

我已经安装了微软官方的C#扩展程序,但它似乎没有帮助。我在VS Code Marketplace中找不到任何代码分析扩展程序,并且在网上搜索时只指向Visual Studio的扩展程序。我也知道可以通过NuGet安装FxCop,但它似乎只适用于Visual Studio。

有没有任何可以与VS Code一起使用的C#代码分析工具?即使是外部工具或dotnet命令也会有所帮助。


1
你尝试过这个 https://www.strathweb.com/2019/04/roslyn-analyzers-in-code-fixes-in-omnisharp-and-vs-code/ 吗?当时它似乎还在进行中,不确定今天是否已经可以用于主流了。 - Martheen
@Martheen 嘿,这个方法可行!你能把它发表为答案,这样我就可以接受了吗?非常感谢! :) - Floating Sunfish
1
可以随意自己发布答案,特别是因为您可以指出要启用哪个配置。我现在没有VS Code,而且我不确定他们没有移动东西。 - Martheen
@Martheen 好的!;) - Floating Sunfish
2个回答

14

特别感谢Martheen推荐了此链接

我只需要将以下内容添加到我的VS Code设置中,就能启用更好的代码分析:

"omnisharp.enableRoslynAnalyzers": true // Enable C# code analysis.

1
这可能很明显,但我实际上搞砸了: 您必须在 Unity 项目中“启用” VS Code https://vionixstudio.com/2021/11/02/unity-visual-studio-code/
  1. 打开 Unity 项目。
  2. 编辑 -> 首选项 -> (分析)外部工具。
  3. 将“外部脚本编辑器”更改为 VS Code。
  4. 单击“重新生成项目文件”。

如果单击脚本,则应打开 VS Code 并且代码完成应该可以正常工作(至少只要其他所有设置都正确,它对我有用)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接