類庫定義了可以從任何應(yīng)用程序調(diào)用的類型和方法。
現(xiàn)在開始在控制臺應(yīng)用程序中添加一個類庫項目(以前創(chuàng)建的FirstApp項目為基礎(chǔ)); 右鍵單擊解決方案資源管理器 ,然后選擇:添加 -> 新建項目…,如下圖所示 -
在“添加新項目”對話框中,選擇“.NET Core”節(jié)點,然后選擇“類庫”(.NET Core)項目模板。
在項目名稱文本框中,輸入“UtilityLibrary”作為項目的名稱,如下圖所示 -

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

在中間窗格中選擇類并在名稱和字段中輸入StringLib.cs,然后單擊添加。 當(dāng)類添加了之后,打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包含一些方法,例如:StartsWithUpper,StartsWithLower和StartsWithNumber,它們返回一個布爾值,指示當(dāng)前字符串實例是否分別以大寫,小寫和數(shù)字開頭。Char.IsUpper方法返回true;如果字符是小寫字符,則Char.IsLower方法返回true;如果字符是數(shù)字字符,則Char.IsNumber方法返回true。為此,展開FirstApp并右鍵單擊在彈出的菜單中選擇:添加 -> 引用 并選擇:添加引用…,如下圖所示 -

在“引用管理器”對話框中,選擇類庫項目UtilityLibrary,然后單擊【確定】。
現(xiàn)在打開控制臺項目的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);
}
}
}
現(xiàn)在運行應(yīng)用程序,將看到以下輸出。如下所示 -

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