温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

top-level如何在C#9 中使用

发布时间:2021-03-31 16:36:41 来源:亿速云 阅读:150 作者:Leah 栏目:开发技术

本篇文章为大家展示了top-level如何在C#9 中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

顶级程序

在 C# 9.0 之前,下面的写法在 Console 程序中已经是最小化的了。

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

在 C# 9.0 时代,可以祭出 顶级程序 来消除那些烦人的模板代码,让代码的逻辑意图更明显,改造后的代码如下:

using System;
Console.WriteLine("Hello World!");

top-level如何在C#9 中使用

顶级程序中的方法

你也可以在顶级程序中使用方法,如下例子所示:

System.Console.WriteLine(DisplayMessage("Joydip!"));
System.Console.Read();
static string DisplayMessage(string name)
{
    return "Hello, " + name;
}

程序跑起来后,控制台将会输出:Hello, Joydip!

top-level如何在C#9 中使用

顶级程序中的类

你也可以在顶级程序中使用类,结构体,枚举,下面的代码展示了如何使用。

System.Console.WriteLine(new Author().DisplayMessage("Joydip!"));
System.Console.Read();
public class Author
{
    public string DisplayMessage(string name)
    {
        return "Hello, " + name;
    }
}

顶级程序的原理分析

现在我们来分析一下,顶级程序的底层逻辑到底是怎么样的,它本质上是一种语法糖,一种编译器的特性,也就是说你没有写模板代码的时候,编译器会帮你生成,替你负重前行,参考下面的代码段。

using System;
Console.WriteLine("Hello World!");

然后用在线工具 SharpLab https://sharplab.io/  看一下编译器替你补齐的代码。

using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[CompilerGenerated]
internal static class <Program>$
{
    private static void <Main>$(string[] args)
    {
        Console.WriteLine("Hello World!");
    }
}

上述内容就是top-level如何在C#9 中使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI