.NET Core創建.NET標準庫

類庫定義了可以從任何應用程式調用的類型和方法。

  • 使用.NET Core開發的類庫支持.NET標準庫,該標準庫允許您的庫由任何支持該版本的.NET標準庫的.NET平臺調用。
  • 當完成類庫時,可以決定是將其作為第三方組件來分發,還是要將其作為與一個或多個應用程式捆綁在一起的組件進行包含。

現在開始在控制臺應用程式中添加一個類庫專案(以前創建的FirstApp專案為基礎); 右鍵單擊解決方案資源管理器 ,然後選擇:添加 -> 新建專案…,如下圖所示 -

“添加新專案”對話框中,選擇“.NET Core”節點,然後選擇“類庫”(.NET Core)專案範本。

在專案名稱文本框中,輸入“UtilityLibrary”作為專案的名稱,如下圖所示 -

單擊確定以創建類庫專案。專案創建完成後,讓我們添加一個新的類。在解決方案資源管理器 中右鍵單擊專案名稱,然後選擇:添加 -> 類…,如下圖所示 -

在中間窗格中選擇類並在名稱和字段中輸入StringLib.cs,然後單擊添加。 當類添加了之後,打StringLib.cs 檔,並編寫下麵的代碼。參考代碼 -

using System;
using System.Collections.Generic;
using System.Text;

namespace UtilityLibrary
{
    public static class StringLib
    {
        public static bool StartsWithUpper(this String str)
        {
            if (String.IsNullOrWhiteSpace(str))
                return false;
            Char ch = str[0];
            return Char.IsUpper(ch);
        }
        public static bool StartsWithLower(this String str)
        {
            if (String.IsNullOrWhiteSpace(str))
                return false;
            Char ch = str[0];
            return Char.IsLower(ch);
        }
        public static bool StartsWithNumber(this String str)
        {
            if (String.IsNullOrWhiteSpace(str))
                return false;
            Char ch = str[0];
            return Char.IsNumber(ch);
        }
    }
}
  • 類庫UtilityLibrary.StringLib包含一些方法,例如:StartsWithUpperStartsWithLowerStartsWithNumber,它們返回一個布爾值,指示當前字串實例是否分別以大寫,小寫和數字開頭。
  • 在.NET Core中,如果字元是大寫字元,則Char.IsUpper方法返回true;如果字元是小寫字元,則Char.IsLower方法返回true;如果字元是數字字元,則Char.IsNumber方法返回true
  • 在菜單欄上,選擇Build,Build Solution。 該專案應該編譯沒有錯誤。
  • .NET Core控制臺專案無法訪問這個類庫。
  • 現在要使用這個類庫,需要在控制臺專案中添加這個類庫的引用。

為此,展開FirstApp並右鍵單擊在彈出的菜單中選擇:添加 -> 引用 並選擇:添加引用…,如下圖所示 -

“引用管理器”對話框中,選擇類庫專案UtilityLibrary,然後單擊【確定】。
現在打開控制臺專案的Program.cs檔,並用下麵的代碼替換所有的代碼。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UtilityLibrary;

namespace FirstApp {
   public class Program {
      public static void Main(string[] args) {
         int rows = Console.WindowHeight;
         Console.Clear();
         do {
            if (Console.CursorTop >= rows || Console.CursorTop == 0) {
               Console.Clear();
               Console.WriteLine("\nPress <Enter> only to exit; otherwise, enter a string and press <Enter>:\n");
            }
            string input = Console.ReadLine();

            if (String.IsNullOrEmpty(input)) break;
            Console.WriteLine("Input: {0} {1,30}: {2}\n", input, "Begins with uppercase? ",
            input.StartsWithUpper() ? "Yes" : "No");
         } while (true);
      }
   }
}

現在運行應用程式,將看到以下輸出。如下所示 -

為了更好的理解,在接下來的章節中也會涉及到如何在專案中使用類庫的其他擴展方法。


上一篇: .Windows運行時和擴展SDK 下一篇: .NET Core可移植類庫