在本章中,我们将讨论什么是pcl(可移植类库),以及为什么我们需要pcl。 为了理解这个概念,让我们打开在前面章创建的类库项目文件夹。
在这个文件夹中,除了project.json
和cs文件之外,还可以看到*.xproj
文件,这是因为visual studio安装.net core项目类型为* .xproj
而不是*.csproj
。
正如微软所提到的,*.xproj
将会消失,但它仍然在预览工具中。uwp应用程序使用*.csproj
。
现在把* .csproj
引用和* .xproj
实际上是不可行的,而且这个功能不会被执行,因为* .xproj
将会移出。
相反,我们需要一个可以在控制台应用程序和uwp应用程序之间共享的类库,这就是pcl。
下面来了解pcl是什么 -
要从解决方案资源管理器创建类库,这里以前面创建的项目: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应用程序也将使用相同的可移植库。