类库定义了可以从任何应用程序调用的类型和方法。
现在开始在控制台应用程序中添加一个类库项目(以前创建的firstapp项目为基础); 右键单击解决方案资源管理器 ,然后选择:添加 -> 新建项目…,如下图所示 -
在“添加新项目”对话框中,选择“.net core”节点,然后选择“类库”(.net core)项目模板。
在项目名称文本框中,输入“utilitylibrary”作为项目的名称,如下图所示 -
单击确定以创建类库项目。项目创建完成后,让我们添加一个新的类。在解决方案资源管理器 中右键单击项目名称,然后选择:添加 -> 类…,如下图所示 -
在中间窗格中选择类并在名称和字段中输入stringlib.cs
,然后单击添加。 当类添加了之后,打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
,它们返回一个布尔值,指示当前字符串实例是否分别以大写,小写和数字开头。char.isupper
方法返回true
;如果字符是小写字符,则char.islower
方法返回true
;如果字符是数字字符,则char.isnumber
方法返回true
。为此,展开firstapp
并右键单击在弹出的菜单中选择:添加 -> 引用 并选择:添加引用…,如下图所示 -
在“引用管理器”对话框中,选择类库项目utilitylibrary
,然后单击【确定】。
现在打开控制台项目的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);
}
}
}
现在运行应用程序,将看到以下输出。如下所示 -
为了更好的理解,在接下来的章节中也会涉及到如何在项目中使用类库的其他扩展方法。