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

單擊確定以創(chuàng)建類庫(kù)項(xiàng)目。項(xiàng)目創(chuàng)建完成后,讓我們添加一個(gè)新的類。在解決方案資源管理器 中右鍵單擊項(xià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,它們返回一個(gè)布爾值,指示當(dāng)前字符串實(shí)例是否分別以大寫,小寫和數(shù)字開(kāi)頭。Char.IsUpper方法返回true;如果字符是小寫字符,則Char.IsLower方法返回true;如果字符是數(shù)字字符,則Char.IsNumber方法返回true。為此,展開(kāi)FirstApp并右鍵單擊在彈出的菜單中選擇:添加 -> 引用 并選擇:添加引用…,如下圖所示 -

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

為了更好的理解,在接下來(lái)的章節(jié)中也會(huì)涉及到如何在項(xiàng)目中使用類庫(kù)的其他擴(kuò)展方法。