教學課程:使用 Visual Studio Code 建立 .NET 類別庫

在本教學課程中,您會建立一個含有單一字串處理方法的簡單公用程式庫。

「類別庫」會定義應用程式所呼叫的類型和方法。 如果程式庫以 NET Standard 2.0 為目標,則可以由任何支援 .NET Standard 2.0 的 .NET 實作 (包括 .NET Framework) 呼叫。 如果程式庫以 .NET 8 為目標,則任何以 .NET 8 目標的應用程式都能加以呼叫。 本教學課程說明如何以 .NET 8 為目標。

您建立類別庫時,您可以將此發佈為協力廠商元件,或發佈為包含一個或多個應用程式的配套元件。

必要條件

建立解決方案

首先,建立空白解決方案,將類別庫專案放入其中。 解決方案做為一個或多個專案的容器。 請將其他相關專案新增至相同的解決方案。

  1. 啟動 Visual Studio Code。

  2. 在主要功能表中依序選擇 [檔案]>[開啟資料夾] (在 macOS 上選擇[開啟...])。

  3. 在 [開啟資料夾] 對話方塊中,建立 ClassLibraryProjects 資料夾,並且按一下 [選取資料夾] (在 macOS 上按一下 [開啟])。

  4. 在主要功能表內選取 [檢視]>[終端],便能於 Visual Studio Code 中開啟 [終端]

    終端會在 ClassLibraryProjects 資料夾中以命令提示字元開啟。

  5. 終端中輸入下列命令:

    dotnet new sln
    

    終端輸出看起來會像下列範例所示:

    The template "Solution File" was created successfully.
    

建立類別庫專案

將名為「StringLibrary」的新 .NET 類別庫專案新增至解決方案。

  1. 在終端中,執行下列命令來建立程式庫專案:

    dotnet new classlib -o StringLibrary
    

    -o--output 命令會指定要將產生的輸出放入的位置。

    終端輸出看起來會像下列範例所示:

    The template "Class library" was created successfully.
    Processing post-creation actions...
    Running 'dotnet restore' on StringLibrary\StringLibrary.csproj...
      Determining projects to restore...
      Restored C:\Projects\ClassLibraryProjects\StringLibrary\StringLibrary.csproj (in 328 ms).
    Restore succeeded.
    
  2. 執行下列命令,將程式庫專案新增至方案:

    dotnet sln add StringLibrary/StringLibrary.csproj
    

    終端輸出看起來會像下列範例所示:

    Project `StringLibrary\StringLibrary.csproj` added to the solution.
    
  3. 檢查以確定程式庫以 .NET 8 為目標。 在 [Explorer]中,開啟 StringLibrary/StringLibrary.csproj

    TargetFramework 元素顯示專案以 .NET 8.0 為目標。

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
      </PropertyGroup>
    
    </Project>
    
  4. 開啟 Class1.cs,並以下列程式碼取代此程式碼。

    namespace UtilityLibraries;
    
    public static class StringLibrary
    {
        public static bool StartsWithUpper(this string? str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return false;
    
            char ch = str[0];
            return char.IsUpper(ch);
        }
    }
    

    類別庫 UtilityLibraries.StringLibrary 包含名為 StartsWithUpper 的方法。 此方法會傳回 Boolean 值,顯示目前字串的執行個體開頭字元是否為大寫。 Unicode 標準會區別大寫和小寫字元。 如果是大寫字元,Char.IsUpper(Char) 方法會傳回 true

    系統會以 擴充方法形式實作 StartsWithUpper,讓您可以將它做為 String 類別的成員來進行呼叫。

  5. 儲存檔案。

  6. 執行下列命令來建置解決方案,並確認專案編譯時不會發生錯誤。

    dotnet build
    

    終端輸出看起來會像下列範例所示:

    Microsoft (R) Build Engine version 17.8.0+b89cb5fde for .NET
    Copyright (C) Microsoft Corporation. All rights reserved.
      Determining projects to restore...
      All projects are up-to-date for restore.
      StringLibrary -> C:\Projects\ClassLibraryProjects\StringLibrary\bin\Debug\net8.0\StringLibrary.dll
    Build succeeded.
        0 Warning(s)
        0 Error(s)
    Time Elapsed 00:00:02.78
    

將主控台應用程式新增至解決方案

新增使用類別庫的主控台應用程式。 應用程式會提示使用者輸入字串,並回報字串是否以大寫字元開頭。

  1. 在終端中,執行下列命令來建立主控台應用程式專案:

    dotnet new console -o ShowCase
    

    終端輸出看起來會像下列範例所示:

    The template "Console Application" was created successfully.
    Processing post-creation actions...
    Running 'dotnet restore' on ShowCase\ShowCase.csproj...
      Determining projects to restore...
      Restored C:\Projects\ClassLibraryProjects\ShowCase\ShowCase.csproj (in 210 ms).
    Restore succeeded.
    
  2. 執行下列命令,新增主控台應用程式專案至解決方案:

    dotnet sln add ShowCase/ShowCase.csproj
    

    終端輸出看起來會像下列範例所示:

    Project `ShowCase\ShowCase.csproj` added to the solution.
    
  3. 開啟 ShowCase/Program.cs,並將所有程式碼取代為下列程式碼。

    using UtilityLibraries;
    
    class Program
    {
        static void Main(string[] args)
        {
            int row = 0;
    
            do
            {
                if (row == 0 || row >= 25)
                    ResetConsole();
    
                string? input = Console.ReadLine();
                if (string.IsNullOrEmpty(input)) break;
                Console.WriteLine($"Input: {input}");
                Console.WriteLine("Begins with uppercase? " +
                     $"{(input.StartsWithUpper() ? "Yes" : "No")}");
                Console.WriteLine();
                row += 4;
            } while (true);
            return;
    
            // Declare a ResetConsole local method
            void ResetConsole()
            {
                if (row > 0)
                {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
                Console.Clear();
                Console.WriteLine($"{Environment.NewLine}Press <Enter> only to exit; otherwise, enter a string and press <Enter>:{Environment.NewLine}");
                row = 3;
            }
        }
    }
    

    該程式碼會使用 row 變數來維護寫入至主控台視窗的資料列數目計數。 當它大於或等於 25 時,程式碼就會清除主控台視窗,並向使用者顯示訊息。

    此程式會提示使用者輸入字串。 它會指出該字串開頭是否為大寫字元。 如果使用者未輸入字串就按 Enter 鍵,應用程式會終止且主控台視窗會關閉。

  4. 儲存您的變更。

新增專案參考

一開始,新的主控台應用程式專案沒有類別庫的存取權。 若要讓該專案在類別庫中呼叫方法,請建立類別庫專案的專案參考。

  1. 執行以下命令:

    dotnet add ShowCase/ShowCase.csproj reference StringLibrary/StringLibrary.csproj
    

    終端輸出看起來會像下列範例所示:

    Reference `..\StringLibrary\StringLibrary.csproj` added to the project.
    

執行應用程式

  1. 在終端中執行下列命令:

    dotnet run --project ShowCase/ShowCase.csproj
    
  2. 輸入字串並按下 Enter 鍵以試用程式。再次按下 Enter 鍵即可結束程式。

    終端輸出看起來會像下列範例所示:

    Press <Enter> only to exit; otherwise, enter a string and press <Enter>:
    
    A string that starts with an uppercase letter
    Input: A string that starts with an uppercase letter
    Begins with uppercase? : Yes
    
    a string that starts with a lowercase letter
    Input: a string that starts with a lowercase letter
    Begins with uppercase? : No
    

其他資源

下一步

在本教學課程中,您建立瞭解決方案、新增了程式庫專案,並且新增了使用該程式庫的主控台應用程式專案。 在下一個教學課程中,您會新增單元測試至解決方案。

在本教學課程中,您會建立一個含有單一字串處理方法的簡單公用程式庫。

「類別庫」會定義應用程式所呼叫的類型和方法。 如果程式庫以 NET Standard 2.0 為目標,則可以由任何支援 .NET Standard 2.0 的 .NET 實作 (包括 .NET Framework) 呼叫。 如果程式庫以 .NET 7 為目標,則任何以 .NET 7 目標的應用程式都能加以呼叫。 本教學課程說明如何以 .NET 7 為目標。

您建立類別庫時,您可以將此發佈為協力廠商元件,或發佈為包含一個或多個應用程式的配套元件。

必要條件

建立解決方案

首先,建立空白解決方案,將類別庫專案放入其中。 解決方案做為一個或多個專案的容器。 請將其他相關專案新增至相同的解決方案。

  1. 啟動 Visual Studio Code。

  2. 在主要功能表中依序選擇 [檔案]>[開啟資料夾] (在 macOS 上選擇[開啟...])。

  3. 在 [開啟資料夾] 對話方塊中,建立 ClassLibraryProjects 資料夾,並且按一下 [選取資料夾] (在 macOS 上按一下 [開啟])。

  4. 在主要功能表內選取 [檢視]>[終端],便能於 Visual Studio Code 中開啟 [終端]

    終端會在 ClassLibraryProjects 資料夾中以命令提示字元開啟。

  5. 終端中輸入下列命令:

    dotnet new sln
    

    終端輸出看起來會像下列範例所示:

    The template "Solution File" was created successfully.
    

建立類別庫專案

將名為「StringLibrary」的新 .NET 類別庫專案新增至解決方案。

  1. 在終端中,執行下列命令來建立程式庫專案:

    dotnet new classlib -o StringLibrary
    

    -o--output 命令會指定要將產生的輸出放入的位置。

    終端輸出看起來會像下列範例所示:

    The template "Class library" was created successfully.
    Processing post-creation actions...
    Running 'dotnet restore' on StringLibrary\StringLibrary.csproj...
      Determining projects to restore...
      Restored C:\Projects\ClassLibraryProjects\StringLibrary\StringLibrary.csproj (in 328 ms).
    Restore succeeded.
    
  2. 執行下列命令,將程式庫專案新增至方案:

    dotnet sln add StringLibrary/StringLibrary.csproj
    

    終端輸出看起來會像下列範例所示:

    Project `StringLibrary\StringLibrary.csproj` added to the solution.
    
  3. 檢查以確定程式庫以 .NET 7 為目標。 在 [Explorer]中,開啟 StringLibrary/StringLibrary.csproj

    TargetFramework 元素顯示專案以 .NET 7.0 為目標。

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net7.0</TargetFramework>
      </PropertyGroup>
    
    </Project>
    
  4. 開啟 Class1.cs,並以下列程式碼取代此程式碼。

    namespace UtilityLibraries;
    
    public static class StringLibrary
    {
        public static bool StartsWithUpper(this string? str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return false;
    
            char ch = str[0];
            return char.IsUpper(ch);
        }
    }
    

    類別庫 UtilityLibraries.StringLibrary 包含名為 StartsWithUpper 的方法。 此方法會傳回 Boolean 值,顯示目前字串的執行個體開頭字元是否為大寫。 Unicode 標準會區別大寫和小寫字元。 如果是大寫字元,Char.IsUpper(Char) 方法會傳回 true

    系統會以 擴充方法形式實作 StartsWithUpper,讓您可以將它做為 String 類別的成員來進行呼叫。

  5. 儲存檔案。

  6. 執行下列命令來建置解決方案,並確認專案編譯時不會發生錯誤。

    dotnet build
    

    終端輸出看起來會像下列範例所示:

    Microsoft (R) Build Engine version 16.7.4+b89cb5fde for .NET
    Copyright (C) Microsoft Corporation. All rights reserved.
      Determining projects to restore...
      All projects are up-to-date for restore.
      StringLibrary -> C:\Projects\ClassLibraryProjects\StringLibrary\bin\Debug\net7.0\StringLibrary.dll
    Build succeeded.
        0 Warning(s)
        0 Error(s)
    Time Elapsed 00:00:02.78
    

將主控台應用程式新增至解決方案

新增使用類別庫的主控台應用程式。 應用程式會提示使用者輸入字串,並回報字串是否以大寫字元開頭。

  1. 在終端中,執行下列命令來建立主控台應用程式專案:

    dotnet new console -o ShowCase
    

    終端輸出看起來會像下列範例所示:

    The template "Console Application" was created successfully.
    Processing post-creation actions...
    Running 'dotnet restore' on ShowCase\ShowCase.csproj...
      Determining projects to restore...
      Restored C:\Projects\ClassLibraryProjects\ShowCase\ShowCase.csproj (in 210 ms).
    Restore succeeded.
    
  2. 執行下列命令,新增主控台應用程式專案至解決方案:

    dotnet sln add ShowCase/ShowCase.csproj
    

    終端輸出看起來會像下列範例所示:

    Project `ShowCase\ShowCase.csproj` added to the solution.
    
  3. 開啟 ShowCase/Program.cs,並將所有程式碼取代為下列程式碼。

    using UtilityLibraries;
    
    class Program
    {
        static void Main(string[] args)
        {
            int row = 0;
    
            do
            {
                if (row == 0 || row >= 25)
                    ResetConsole();
    
                string? input = Console.ReadLine();
                if (string.IsNullOrEmpty(input)) break;
                Console.WriteLine($"Input: {input}");
                Console.WriteLine("Begins with uppercase? " +
                     $"{(input.StartsWithUpper() ? "Yes" : "No")}");
                Console.WriteLine();
                row += 4;
            } while (true);
            return;
    
            // Declare a ResetConsole local method
            void ResetConsole()
            {
                if (row > 0)
                {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
                Console.Clear();
                Console.WriteLine($"{Environment.NewLine}Press <Enter> only to exit; otherwise, enter a string and press <Enter>:{Environment.NewLine}");
                row = 3;
            }
        }
    }
    

    該程式碼會使用 row 變數來維護寫入至主控台視窗的資料列數目計數。 當它大於或等於 25 時,程式碼就會清除主控台視窗,並向使用者顯示訊息。

    此程式會提示使用者輸入字串。 它會指出該字串開頭是否為大寫字元。 如果使用者未輸入字串就按 Enter 鍵,應用程式會終止且主控台視窗會關閉。

  4. 儲存您的變更。

新增專案參考

一開始,新的主控台應用程式專案沒有類別庫的存取權。 若要讓該專案在類別庫中呼叫方法,請建立類別庫專案的專案參考。

  1. 執行以下命令:

    dotnet add ShowCase/ShowCase.csproj reference StringLibrary/StringLibrary.csproj
    

    終端輸出看起來會像下列範例所示:

    Reference `..\StringLibrary\StringLibrary.csproj` added to the project.
    

執行應用程式

  1. 在終端中執行下列命令:

    dotnet run --project ShowCase/ShowCase.csproj
    
  2. 輸入字串並按下 Enter 鍵以試用程式。再次按下 Enter 鍵即可結束程式。

    終端輸出看起來會像下列範例所示:

    Press <Enter> only to exit; otherwise, enter a string and press <Enter>:
    
    A string that starts with an uppercase letter
    Input: A string that starts with an uppercase letter
    Begins with uppercase? : Yes
    
    a string that starts with a lowercase letter
    Input: a string that starts with a lowercase letter
    Begins with uppercase? : No
    

其他資源

下一步

在本教學課程中,您建立瞭解決方案、新增了程式庫專案,並且新增了使用該程式庫的主控台應用程式專案。 在下一個教學課程中,您會新增單元測試至解決方案。

在本教學課程中,您會建立一個含有單一字串處理方法的簡單公用程式庫。

「類別庫」會定義應用程式所呼叫的類型和方法。 如果程式庫以 NET Standard 2.0 為目標,則可以由任何支援 .NET Standard 2.0 的 .NET 實作 (包括 .NET Framework) 呼叫。 如果程式庫以 .NET 6 為目標,則任何以 .NET 6 目標的應用程式都能加以呼叫。 本教學課程說明如何以 .NET 6 為目標。

您建立類別庫時,您可以將此發佈為協力廠商元件,或發佈為包含一個或多個應用程式的配套元件。

必要條件

建立解決方案

首先,建立空白解決方案,將類別庫專案放入其中。 解決方案做為一個或多個專案的容器。 請將其他相關專案新增至相同的解決方案。

  1. 啟動 Visual Studio Code。

  2. 在主要功能表中依序選擇 [檔案]>[開啟資料夾] (在 macOS 上選擇[開啟...])。

  3. 在 [開啟資料夾] 對話方塊中,建立 ClassLibraryProjects 資料夾,並且按一下 [選取資料夾] (在 macOS 上按一下 [開啟])。

  4. 在主要功能表內選取 [檢視]>[終端],便能於 Visual Studio Code 中開啟 [終端]

    終端會在 ClassLibraryProjects 資料夾中以命令提示字元開啟。

  5. 終端中輸入下列命令:

    dotnet new sln
    

    終端輸出看起來會像下列範例所示:

    The template "Solution File" was created successfully.
    

建立類別庫專案

將名為「StringLibrary」的新 .NET 類別庫專案新增至解決方案。

  1. 在終端中,執行下列命令來建立程式庫專案:

    dotnet new classlib -f net6.0 -o StringLibrary
    

    命令 -f--framework 會將預設目標框架變更為 net6.0 版本。

    -o--output 命令會指定要將產生的輸出放入的位置。

    終端輸出看起來會像下列範例所示:

    The template "Class library" was created successfully.
    Processing post-creation actions...
    Running 'dotnet restore' on StringLibrary\StringLibrary.csproj...
      Determining projects to restore...
      Restored C:\Projects\ClassLibraryProjects\StringLibrary\StringLibrary.csproj (in 328 ms).
    Restore succeeded.
    
  2. 執行下列命令,將程式庫專案新增至方案:

    dotnet sln add StringLibrary/StringLibrary.csproj
    

    終端輸出看起來會像下列範例所示:

    Project `StringLibrary\StringLibrary.csproj` added to the solution.
    
  3. 檢查以確定程式庫以 .NET 6 為目標。 在 [Explorer]中,開啟 StringLibrary/StringLibrary.csproj

    TargetFramework 元素顯示專案以 .NET 6.0 為目標。

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
    </Project>
    
  4. 開啟 Class1.cs,並以下列程式碼取代此程式碼。

    namespace UtilityLibraries;
    
    public static class StringLibrary
    {
        public static bool StartsWithUpper(this string? str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return false;
    
            char ch = str[0];
            return char.IsUpper(ch);
        }
    }
    

    類別庫 UtilityLibraries.StringLibrary 包含名為 StartsWithUpper 的方法。 此方法會傳回 Boolean 值,顯示目前字串的執行個體開頭字元是否為大寫。 Unicode 標準會區別大寫和小寫字元。 如果是大寫字元,Char.IsUpper(Char) 方法會傳回 true

    系統會以 擴充方法形式實作 StartsWithUpper,讓您可以將它做為 String 類別的成員來進行呼叫。

  5. 儲存檔案。

  6. 執行下列命令來建置解決方案,並確認專案編譯時不會發生錯誤。

    dotnet build
    

    終端輸出看起來會像下列範例所示:

    Microsoft (R) Build Engine version 16.7.0+b89cb5fde for .NET
    Copyright (C) Microsoft Corporation. All rights reserved.
      Determining projects to restore...
      All projects are up-to-date for restore.
      StringLibrary -> C:\Projects\ClassLibraryProjects\StringLibrary\bin\Debug\net6.0\StringLibrary.dll
    Build succeeded.
        0 Warning(s)
        0 Error(s)
    Time Elapsed 00:00:02.78
    

將主控台應用程式新增至解決方案

新增使用類別庫的主控台應用程式。 應用程式會提示使用者輸入字串,並回報字串是否以大寫字元開頭。

  1. 在終端中,執行下列命令來建立主控台應用程式專案:

    dotnet new console -f net6.0 -o ShowCase
    

    終端輸出看起來會像下列範例所示:

    The template "Console Application" was created successfully.
    Processing post-creation actions...
    Running 'dotnet restore' on ShowCase\ShowCase.csproj...
      Determining projects to restore...
      Restored C:\Projects\ClassLibraryProjects\ShowCase\ShowCase.csproj (in 210 ms).
    Restore succeeded.
    
  2. 執行下列命令,新增主控台應用程式專案至解決方案:

    dotnet sln add ShowCase/ShowCase.csproj
    

    終端輸出看起來會像下列範例所示:

    Project `ShowCase\ShowCase.csproj` added to the solution.
    
  3. 開啟 ShowCase/Program.cs,並將所有程式碼取代為下列程式碼。

    using UtilityLibraries;
    
    class Program
    {
        static void Main(string[] args)
        {
            int row = 0;
    
            do
            {
                if (row == 0 || row >= 25)
                    ResetConsole();
    
                string? input = Console.ReadLine();
                if (string.IsNullOrEmpty(input)) break;
                Console.WriteLine($"Input: {input}");
                Console.WriteLine("Begins with uppercase? " +
                     $"{(input.StartsWithUpper() ? "Yes" : "No")}");
                Console.WriteLine();
                row += 4;
            } while (true);
            return;
    
            // Declare a ResetConsole local method
            void ResetConsole()
            {
                if (row > 0)
                {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
                Console.Clear();
                Console.WriteLine($"{Environment.NewLine}Press <Enter> only to exit; otherwise, enter a string and press <Enter>:{Environment.NewLine}");
                row = 3;
            }
        }
    }
    

    該程式碼會使用 row 變數來維護寫入至主控台視窗的資料列數目計數。 當它大於或等於 25 時,程式碼就會清除主控台視窗,並向使用者顯示訊息。

    此程式會提示使用者輸入字串。 它會指出該字串開頭是否為大寫字元。 如果使用者未輸入字串就按 Enter 鍵,應用程式會終止且主控台視窗會關閉。

  4. 儲存您的變更。

新增專案參考

一開始,新的主控台應用程式專案沒有類別庫的存取權。 若要讓該專案在類別庫中呼叫方法,請建立類別庫專案的專案參考。

  1. 執行以下命令:

    dotnet add ShowCase/ShowCase.csproj reference StringLibrary/StringLibrary.csproj
    

    終端輸出看起來會像下列範例所示:

    Reference `..\StringLibrary\StringLibrary.csproj` added to the project.
    

執行應用程式

  1. 在終端中執行下列命令:

    dotnet run --project ShowCase/ShowCase.csproj
    
  2. 輸入字串並按下 Enter 鍵以試用程式。再次按下 Enter 鍵即可結束程式。

    終端輸出看起來會像下列範例所示:

    Press <Enter> only to exit; otherwise, enter a string and press <Enter>:
    
    A string that starts with an uppercase letter
    Input: A string that starts with an uppercase letter
    Begins with uppercase? : Yes
    
    a string that starts with a lowercase letter
    Input: a string that starts with a lowercase letter
    Begins with uppercase? : No
    

其他資源

下一步

在本教學課程中,您建立瞭解決方案、新增了程式庫專案,並且新增了使用該程式庫的主控台應用程式專案。 在下一個教學課程中,您會新增單元測試至解決方案。