使用命令列開始在 Windows/Linux/macOS 上使用 .NET CoreGet started with .NET Core on Windows/Linux/macOS using the command line

本主題將示範如何使用 .NET Core CLI 工具在電腦上開始開發跨平台應用程式。This topic will show you how to start developing cross-platforms apps in your machine using the .NET Core CLI tools.

如果您不熟悉 .NET Core CLI 工具組,請參閱 .NET Core SDK 概觀If you're unfamiliar with the .NET Core CLI toolset, read the .NET Core SDK overview.

必要條件Prerequisites

嗨,主控台應用程式!Hello, Console App!

您可以從 dotnet/samples GitHub 存放庫檢視或下載範例程式碼You can view or download the sample code from the dotnet/samples GitHub repository. 如需下載指示,請參閱範例和教學課程For download instructions, see Samples and Tutorials.

開啟命令提示字元,並建立名為 Hello 的資料夾。Open a command prompt and create a folder named Hello. 巡覽至您已建立的資料夾,並鍵入下列內容:Navigate to the folder you created and type the following:

dotnet new console
dotnet run

讓我們快速逐步解說︰Let's do a quick walkthrough:

  1. dotnet new console

    dotnet new 使用建置主控台應用程式時所需的相依性,來建立最新的 Hello.csproj 專案檔。dotnet new creates an up-to-date Hello.csproj project file with the dependencies necessary to build a console app. 它也會建立 Program.cs,這個基本檔案包含了應用程式的進入點。It also creates a Program.cs, a basic file containing the entry point for the application.

    Hello.csprojHello.csproj:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.2</TargetFramework>
      </PropertyGroup>
    
    </Project>
    

    專案檔會指定還原相依性和建置程式所需的所有內容。The project file specifies everything that's needed to restore dependencies and build the program.

    • OutputType 標記會指定我們正在建置可執行檔,亦即主控台應用程式。The OutputType tag specifies that we're building an executable, in other words a console application.
    • TargetFramework 標記會指定做為目標的 .NET 實作。The TargetFramework tag specifies what .NET implementation we're targeting. 在進階案例中,您可以指定多個目標架構,並在單一作業中建置這全部的架構。In an advanced scenario, you can specify multiple target frameworks and build to all those in a single operation. 在本教學課程中,我們將著重於僅針對 .NET Core 2.1 來建置。In this tutorial, we'll stick to building only for .NET Core 2.1.

    Program.csProgram.cs:

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

    程式是透過 using System 來啟動,這表示「將 System 命名空間中的所有內容帶入這個檔案的範圍內」。The program starts by using System, which means "bring everything in the System namespace into scope for this file". System 命名空間會包含像是 string 的基本結構或數字類型。The System namespace includes basic constructs such as string, or numeric types.

    然後,我們會定義稱為 Hello 的命名空間。We then define a namespace called Hello. 您可以將其變更為任何所需的位置。You can change this to anything you want. 名為 Program 的類別是定義於該命名空間內,其中含有可接受字串陣列作為其引數的 Main 方法。A class named Program is defined within that namespace, with a Main method that takes an array of strings as its argument. 這個陣列包含呼叫已編譯的程式時傳入的引數清單。This array contains the list of arguments passed in when the compiled program is called. 事實上,並未使用這個陣列︰所有程式所做的只是將 "Hello World!" 寫入As it is, this array is not used: all the program is doing is to write "Hello World!" 到主控台。to the console. 稍後,我們將變更程式碼以便使用此引數。Later, we'll make changes to the code that will make use of this argument.

    注意

    從 .NET Core 2.0 SDK 開始,您不需要執行 dotnet restore,因為所有需要進行還原的命令 (例如 dotnet newdotnet builddotnet run) 都會以隱含方式執行它。Starting with .NET Core 2.0 SDK, you don't have to run dotnet restore because it's run implicitly by all commands that require a restore to occur, such as dotnet new, dotnet build and dotnet run. 它在執行明確還原有意義的某些情況下仍然是有效的命令,例如 Azure DevOps Services 中的持續整合組建,或在需要明確控制還原進行時間的建置系統中。It's still a valid command in certain scenarios where doing an explicit restore makes sense, such as continuous integration builds in Azure DevOps Services or in build systems that need to explicitly control the time at which the restore occurs.

    dotnet new 會隱含地呼叫 dotnet restoredotnet new calls dotnet restore implicitly. dotnet restore 呼叫 NuGet (.NET 套件管理員),以還原相依性的樹狀結構。dotnet restore calls into NuGet (.NET package manager) to restore the tree of dependencies. NuGet 會分析 Hello.csproj 檔案、下載檔案中所述的相依性 (或從您電腦上的快取抓取),並寫入 obj/project.assets.json 檔案,該檔案是編譯及執行範例的必要項目。NuGet analyzes the Hello.csproj file, downloads the dependencies defined in the file (or grabs them from a cache on your machine), and writes the obj/project.assets.json file, which is necessary to compile and run the sample.

    重要

    如果您使用 .NET Core 1.x 版本的 SDK,則必須在呼叫 dotnet new 之後自行呼叫 dotnet restoreIf you're using a .NET Core 1.x version of the SDK, you'll have to call dotnet restore yourself after calling dotnet new.

  2. dotnet run

    dotnet run 呼叫 dotnet build 以確保建置目標已經建置好,然後呼叫 dotnet <assembly.dll> 執行目標應用程式。dotnet run calls dotnet build to ensure that the build targets have been built, and then calls dotnet <assembly.dll> to run the target application.

    $ dotnet run
    Hello World!
    

    或者,您也可以執行 dotnet build 來編譯程式碼,而不執行建置主控台應用程式。Alternatively, you can also execute dotnet build to compile the code without running the build console applications. 這會產生編譯成 DLL 檔案的應用程式,您可以在 Windows 上使用 dotnet bin\Debug\netcoreapp2.1\Hello.dll (在非 Windows 系統上則使用 /) 來執行此應用程式。This results in a compiled application as a DLL file that can be run with dotnet bin\Debug\netcoreapp2.1\Hello.dll on Windows (use / for non-Windows systems). 您也可以指定應用程式的引數,您將於稍後看到該主題。You may also specify arguments to the application as you'll see later on the topic.

    $ dotnet bin\Debug\netcoreapp2.1\Hello.dll
    Hello World!
    

    在進階案例中,可以建置應用程式做為一組獨立的平台專屬檔案,您可以將其部署到不需安裝 .NET Core 的電腦上並加以執行。As an advanced scenario, it's possible to build the application as a self-contained set of platform-specific files that can be deployed and run to a machine that doesn't necessarily have .NET Core installed. 如需詳細資訊,請參閱 .NET Core 應用程式部署See .NET Core Application Deployment for details.

擴充程式Augmenting the program

讓我們稍微變更程式。Let's change the program a bit. Fibonacci 數字很有趣,因此讓我們也新增該數字,以使用引數來歡迎執行應用程式的人員。Fibonacci numbers are fun, so let's add that in addition to use the argument to greet the person running the app.

  1. 以下列程式碼取代 Program.cs 檔案的內容:Replace the contents of your Program.cs file with the following code:

    using System;
    
    namespace Hello
    {
        class Program
        {
            static void Main(string[] args)
            {
                if (args.Length > 0)
                {
                    Console.WriteLine($"Hello {args[0]}!");
                }
                else
                {
                    Console.WriteLine("Hello!");
                }
    
                Console.WriteLine("Fibonacci Numbers 1-15:");
    
                for (int i = 0; i < 15; i++)
                {
                    Console.WriteLine($"{i + 1}: {FibonacciNumber(i)}");
                }
            }
    
            static int FibonacciNumber(int n)
            {
                int a = 0;
                int b = 1;
                int tmp;
    
                for (int i = 0; i < n; i++)
                {
                    tmp = a;
                    a = b;
                    b += tmp;
                }
    
                return a;
            }
    
        }
    }
    
  2. 執行 dotnet build 以編譯變更。Execute dotnet build to compile the changes.

  3. 執行將參數傳遞至應用程式的程式:Run the program passing a parameter to the app:

    $ dotnet run -- John
    Hello John!
    Fibonacci Numbers 1-15:
    1: 0
    2: 1
    3: 1
    4: 2
    5: 3
    6: 5
    7: 8
    8: 13
    9: 21
    10: 34
    11: 55
    12: 89
    13: 144
    14: 233
    15: 377
    

就是這麼容易!And that's it! 您可以隨意擴充 Program.csYou can augment Program.cs any way you like.

使用多個檔案Working with multiple files

單一檔案適用於簡單的一次性程式,但如果您要建置更複雜的應用程式,可能在專案上要具備多個原始程式檔。Single files are fine for simple one-off programs, but if you're building a more complex app, you're probably going to have multiple source files on your project. 請藉由快取某些 Fibonacci 值,再新增一些遞迴功能,從先前的 Fibonacci 範例開始建置。Let's build off of the previous Fibonacci example by caching some Fibonacci values and add some recursive features.

  1. 使用下列程式碼在 Hello 目錄中新增名為 FibonacciGenerator.cs 的檔案:Add a new file inside the Hello directory named FibonacciGenerator.cs with the following code:

    using System;
    using System.Collections.Generic;
    
    namespace Hello
    {
        public class FibonacciGenerator
        {
            private Dictionary<int, int> _cache = new Dictionary<int, int>();
            
            private int Fib(int n) => n < 2 ? n : FibValue(n - 1) + FibValue(n - 2);
            
            private int FibValue(int n)
            {
                if (!_cache.ContainsKey(n))
                {
                    _cache.Add(n, Fib(n));
                }
                
                return _cache[n];
            }
            
            public IEnumerable<int> Generate(int n)
            {
                for (int i = 0; i < n; i++)
                {
                    yield return FibValue(i);
                }
            }
        }
    }
    
  2. 變更 Program.cs 檔案中的 Main 方法,以具現化新的類別並呼叫其方法,如下列範例所示:Change the Main method in your Program.cs file to instantiate the new class and call its method as in the following example:

    using System;
    
    namespace Hello
    {
        class Program
        {
            static void Main(string[] args)
            {
                var generator = new FibonacciGenerator();
                foreach (var digit in generator.Generate(15))
                {
                    Console.WriteLine(digit);
                }
            }
        }
    }
    
  3. 執行 dotnet build 以編譯變更。Execute dotnet build to compile the changes.

  4. 藉由執行 dotnet run 來執行您的應用程式。Run your app by executing dotnet run. 以下顯示程式輸出:The following shows the program output:

    $ dotnet run
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    55
    89
    144
    233
    377
    

就是這麼容易!And that's it! 現在,您可以開始使用這裡學到的基本概念,建立您自己的程式。Now, you can start using the basic concepts learned here to create your own programs.

請注意,本教學課程中所示用於執行應用程式的命令和步驟,僅供開發階段期間使用。Note that the commands and steps shown in this tutorial to run your application are used during development time only. 準備好部署應用程式之後,您將需要檢視不同的 .NET Core 應用程式部署策略dotnet publish 命令。Once you're ready to deploy your app, you'll want to take a look at the different deployment strategies for .NET Core apps and the dotnet publish command.

另請參閱See also