zoukankan      html  css  js  c++  java
  • C# Main方法 -0002

    main方法简介

    • Main方法是C#应用的入口函数,是程序启动时第一个被调用执行的方法;

    • Main方法需要声明在一个class或struct里面;

    • Main方法必须是static方法;

    • Main方法不必是public的

    main方法的定义

    • main方法可以是以下列表中的一个:

    public static void Main() { }
    public static int Main() { }
    public static void Main(string[] args) { }
    public static int Main(string[] args) { }
    public static async Task Main() { }
    public static async Task<int> Main() { }
    public static async Task Main(string[] args) { }
    public static async Task<int> Main(string[] args) { }
    • Task或Task<int>返回值类型,是在C# 7.1及之后的版本支持;

    • 如果返回值是Task或Task<int>类型,需要在前面加 async关键字;

    • 注:public关键字不是必须的,可以省略。

    多个Main方法

    • 当应用程序里面包含多个Main方法的时候,需要在编译的时候使用 /main选项指定入口是哪一个Main方法;

    • 示例:新加一个Hello类,里面也定义一个Main方法:

    using System;
    
    namespace _0002main_method
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine($"this Main method in Program class");
            }
        }
    
        class Hello
        {
            static void Main(string[] args)
            {
                Console.WriteLine($"this Main method in Hello class");
            }
        }
    }
    

    当运行程序(dotnet run)时报错:

    Hello.cs(7,21): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point. The build failed. Fix the build errors and run again.

    多Main方法-解决办法  

    使用csc编译

    csc Program.cs /main:_0002main_method.Hello
    

    使用dotnet build

    dotnet build /p:StartupObject=_0002main_method.Hello
    

    补充说明

    • 不能在dotnet 命令使用/main的原因是:/main参数是编译器(csc)的参数,不是dotnet的;

    • dotnet build本质会去调用MSBuild,MSBuild进而调用csc;所以需要用MSBuild的参数/p指定对应的类,然后其会再转给csc。

  • 相关阅读:
    739. Daily Temperatures
    556. Next Greater Element III
    1078. Occurrences After Bigram
    1053. Previous Permutation With One Swap
    565. Array Nesting
    1052. Grumpy Bookstore Owner
    1051. Height Checker
    数据库入门及SQL基本语法
    ISCSI的概念
    配置一个IP SAN 存储服务器
  • 原文地址:https://www.cnblogs.com/codesee/p/13021521.html
Copyright © 2011-2022 走看看