用户登录
用户注册

分享至

如何在C#9 中使用顶级程序 (top-level)

  • 作者: 容易吗我30141521
  • 来源: 51数据库
  • 2021-09-03

当我们用 c# 进行编码的时候,总需要写很多的模板代码,即使是最简单的 console 程序,想象一下,如果去测试一个 类库 或者 api 的功能,通常你会用 console 程序去实现,在开始工作的时候会发现你受到了 c# 标准模板的限制,业务逻辑必须要写在 main 里,如下代码所示:

    class program
    {
        static void main(string[] args)
        {
            //todo
        }
    }

顶级程序 是 c#9 中引入的一个新概念,允许你直接写自己的业务逻辑而不必受到模板代码的限制,顶级程序 是一个非常🐂👃的特性,可以让代码更加的干净,简短和可读,你可以通过顶级程序去探索新的 idea,这篇文章将会讨论如何在 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!");

顶级程序中的方法

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

system.console.writeline(displaymessage("joydip!"));
system.console.read();
static string displaymessage(string name)
{
    return "hello, " + name;
}

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

顶级程序中的类

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

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 http://www.51sjk.com/Upload/Articles/1/0/260/260573_20210701004000538.jpg  看一下编译器替你补齐的代码。

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!");
    }
}

总的来说,顶级程序 非常适合那些想 快速试错,验证想法 的场景,有一点要特别注意,应用程序中只能仅有一个文件使用 顶级程序,如果存在多个,编译器会抛出错误的,还有一点,如果你是 c# 新手,你可能不理解顶级程序的底层逻辑,更好的方式就是老老实实的使用原生模板代码,当你主宰了 main 后,你将会理解 顶级程序 是多么的短小精悍!

以上就是如何在c#9 中使用顶级程序 (top-level)的详细内容,更多关于c#9 中使用顶级程序 (top-level)的资料请关注其它相关文章!

软件
前端设计
程序设计
Java相关