在本章中,我們將討論什么是PCL(可移植類庫),以及為什么我們需要PCL。 為了理解這個概念,讓我們打開在前面章創(chuàng)建的類庫項(xiàng)目文件夾。

在這個文件夾中,除了project.json和CS文件之外,還可以看到*.xproj文件,這是因?yàn)閂isual Studio安裝.NET Core項(xiàng)目類型為* .xproj而不是*.csproj。
正如微軟所提到的,*.xproj將會消失,但它仍然在預(yù)覽工具中。UWP應(yīng)用程序使用*.csproj。

現(xiàn)在把* .csproj引用和* .xproj實(shí)際上是不可行的,而且這個功能不會被執(zhí)行,因?yàn)?code>* .xproj將會移出。
相反,我們需要一個可以在控制臺應(yīng)用程序和UWP應(yīng)用程序之間共享的類庫,這就是PCL。
下面來了解PCL是什么 -
要從解決方案資源管理器創(chuàng)建類庫,這里以前面創(chuàng)建的項(xiàng)目:FirstApp 為基礎(chǔ),首先點(diǎn)擊解決方案 添加一個新的項(xiàng)目。在左窗格中選擇Visual C# -> Windows 通用 模板,然后在中間窗格中選擇“類庫(通用Windows)” ,如下所示 -

在項(xiàng)目名稱字段中輸入:StringLibrary ,然后單擊確定 以創(chuàng)建此項(xiàng)目?,F(xiàn)在需要選擇目標(biāo)框架來引用。選擇Windows通用和ASP.NET核心片刻,然后重新定位它。點(diǎn)擊【確定】。如下圖所示 -

可以看到它已經(jīng)創(chuàng)建了一個PCF格式的新項(xiàng)目。右鍵單擊解決方案資源管理器中的StringLibrary項(xiàng)目并選擇屬性。

現(xiàn)在添加一個新的類; 需要在解決方案資源管理器中右鍵單擊項(xiàng)目,然后選擇:添加 -> 類… ,輸入類文件的名稱: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);
}
}
}
下面來構(gòu)建這個可移植的類庫項(xiàng)目,并且應(yīng)該編譯沒有錯誤。需要在控制臺項(xiàng)目中添加這個可移植類庫的引用。 因此,展開FirstApp并右鍵單擊 添加-> 引用,并選擇 引用…

在“引用管理器”對話框中,選擇可移植類庫項(xiàng)目:StringLibrary ,然后單擊【確定】。

可以看到StringLibrary引用已添加到控制臺項(xiàng)目中,也可以在Assenblyinfo.json 文件中看到?,F(xiàn)在修改文件: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);
}
}
}
再次運(yùn)行該應(yīng)用程序,將看到相同的輸出。

現(xiàn)在,在項(xiàng)目中使用可移植類庫的其他擴(kuò)展方法。UWP應(yīng)用程序也將使用相同的可移植庫。