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

VSCode中我的C# .NET 7脚本里分号为何显示为红色?

解决VSCode中C# .NET 7代码分号变红的问题

错误原因

代码里的红色分号是因为方法内部不能使用访问修饰符:在Main方法里定义private int test = 0;违反了C#语法规则——局部变量不允许添加private这类类级别的访问修饰符,编译器因此报错,导致分号被标记为红色。

修正方案

方案1:定义局部变量(去掉访问修饰符)

如果test只是Main方法内使用的临时变量,直接去掉private即可:

using System;
namespace CodeWarTests
{
    class Program 
    {          
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            int test = 0;
        }
    }
}

方案2:定义类的私有成员(移到方法外)

如果test需要作为类的私有成员供多个方法使用,要把它移到Main方法外部、类的内部:

using System;
namespace CodeWarTests
{
    class Program 
    {
        private int test = 0;
        
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            // 非静态成员需要通过类实例访问
            Program program = new Program();
            Console.WriteLine(program.test);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:34:55