在本章中,我們將討論什麼是PCL(可移植類庫),以及為什麼我們需要PCL。 為了理解這個概念,讓我們打開在前面章創建的類庫專案檔夾。
在這個檔夾中,除了project.json
和CS檔之外,還可以看到*.xproj
檔,這是因為Visual Studio安裝.NET Core專案類型為* .xproj
而不是*.csproj
。
正如微軟所提到的,*.xproj
將會消失,但它仍然在預覽工具中。UWP應用程式使用*.csproj
。
現在把* .csproj
引用和* .xproj
實際上是不可行的,而且這個功能不會被執行,因為* .xproj
將會移出。
相反,我們需要一個可以在控制臺應用程式和UWP應用程式之間共用的類庫,這就是PCL。
什麼是PCL
下麵來瞭解PCL是什麼 -
- 可移植類庫專案使我們能夠編寫和構建在多個.NET Framework平臺上工作的受管程式集。
- 可以創建包含希望在多個專案(如共用業務邏輯)中共享的代碼的類,然後引用來自不同類型專案的類。
- 它還可以幫助您快速輕鬆地為Microsoft平臺構建跨平臺的應用程式和庫。
- 可移植類庫可以幫助您減少開發和測試代碼的時間和成本。
- 使用此專案類型來編寫和構建可移植的.NET Framework程式集,然後從以Windows和Windows Phone等多個平臺為目標的應用程式中引用這些程式集。
要從解決方案資源管理器創建類庫,這裏以前面創建的專案:FirstApp 為基礎,首先點擊解決方案 添加一個新的專案。在左窗格中選擇Visual C# -> Windows 通用 範本,然後在中間窗格中選擇“類庫(通用Windows)” ,如下所示 -
在專案名稱字段中輸入:StringLibrary ,然後單擊確定 以創建此專案。現在需要選擇目標框架來引用。選擇Windows通用和ASP.NET核心片刻,然後重新定位它。點擊【確定】。如下圖所示 -
可以看到它已經創建了一個PCF格式的新專案。右鍵單擊解決方案資源管理器中的StringLibrary專案並選擇屬性。
現在添加一個新的類; 需要在解決方案資源管理器中右鍵單擊專案,然後選擇:添加 -> 類… ,輸入類檔的名稱:MyStringLib.cs ,如下所示 -
類:MyStringLib.cs -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringLibrary
{
public static class MyStringLib
{
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);
}
}
}
下麵來構建這個可移植的類庫專案,並且應該編譯沒有錯誤。需要在控制臺專案中添加這個可移植類庫的引用。 因此,展開FirstApp並右鍵單擊 添加-> 引用,並選擇 引用…
在“引用管理器”對話框中,選擇可移植類庫專案:StringLibrary ,然後單擊【確定】。
可以看到StringLibrary引用已添加到控制臺專案中,也可以在Assenblyinfo.json 檔中看到。現在修改檔:Program.cs ,如下所示 -
using System;
using StringLibrary;
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);
}
}
}
再次運行該應用程式,將看到相同的輸出。
現在,在專案中使用可移植類庫的其他擴展方法。UWP應用程式也將使用相同的可移植庫。