新的 C# 模板生成顶级语句

377 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第3天,点击查看活动详情

使用visual studio2022,创建的.NET6.0程序的时候,新建项目的时候会遇到顶级语句,
没有Main方法,没有括弧,没有类名,没有引用,程序照样正常运行。

从C#9开始,您不必显式地包含Main方法在控制台应用程序项目中。相反,您可以使用高层声明功能,以最小化您必须编写的代码。

 

在这种情况下,编译器生成一个类并Main方法应用程序的入口点。

这是一个Program.cs文件,该文件是C#10中完整的C#程序:

image.png \

顶级语句的规则:

I 应用程序必须只有一个入口点。项目只能有一个具有顶级语句的文件。
将顶级语句放入项目中的多个文件中将导致以下编译器错误:

image.png

项目可以有许多没有顶级语句的附加源代码文件。

II 没有其他入口点

你可以写一个Main 方法,但它不能充当入口点。编译器发出以下警告: image.png

隐式 using 指令

隐式 using 指令意味着编译器会根据项目类型自动添加一组 using 指令。对于控制台应用程序,以下指令隐式包含在应用程序中:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

其他应用程序类型包括更多对这些应用程序类型通用的命名空间。

如果需要未隐式包含的 using 指令,可以将这些指令添加到包含顶级语句的 .cs 文件或其他 .cs 文件中。

对于应用程序的所有 .cs 文件中所需的 using 指令,请使用using指令

禁用隐式using指令 

如果要删除该行为并手动控制项目中的所有命名空间,请在项目文件中添加

<ImplicitUsings>disable</ImplicitUsings>

使用旧程序样式
虽然 .NET 6 控制台应用模板将生成新样式的顶级语句程序,但使用 .NET 5 则不会。

创建 .NET 5 项目时将获得旧程序样式。然后可以编辑项目文件以使其面向 .NET 6。

如:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace ConsoleApp3
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //
            Console.WriteLine("Hello World!");
            List<string> list = new List<string>();
            int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
            // 2. Query creation.
            // numQuery is an IEnumerable<int>
            var numQuery = from num in numbers where (num % 2) == 0 select num;


            // 3. Query execution.
            foreach (int num in numQuery)
            {
                Console.Write("{0,1} ", num);
            }
            XmlDocument log4NetConfig = new XmlDocument();
            log4NetConfig.Load(Path.Combine(basePath, "Log4net.config"));
        }
    }
}

.NET 6 新的程序样式:

控制台


using System.Xml;


//Console.WriteLine("Hello, World!");


int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery = from num in numbers where (num % 2) == 0 select num;
// 3. Query execution.
foreach (int num in numQuery)
{
    Console.Write("{0,1} ", num);
}
XmlDocument log4NetConfig = new XmlDocument();
log4NetConfig.Load(Path.Combine("basePath", "Log4net.config"));

后端服务WebApi:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run(); 

调用其他方法和类

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

var bll = new TestInfo();
bll.test();

TestInfo model =new TestInfo();
model.name = "张三";

Console.WriteLine(JsonConvert.SerializeObject(model));


public class TestInfo
{
    /// <summary>
    /// name
    /// </summary>
   public string name { get; set; }

    public void test()
    {
        Console.WriteLine("Hello, World2222");
    }
}

.NET 6 新增的这种方式,代码看起来极其精简;但是和之前相比却不易理解