.NET Core创建.NET标准库

类库定义了可以从任何应用程序调用的类型和方法。

  • 使用.NET Core开发的类库支持.NET标准库,该标准库允许您的库由任何支持该版本的.NET标准库的.NET平台调用。
  • 当完成类库时,可以决定是将其作为第三方组件来分发,还是要将其作为与一个或多个应用程序捆绑在一起的组件进行包含。

现在开始在控制台应用程序中添加一个类库项目(以前创建的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包含一些方法,例如:StartsWithUpperStartsWithLowerStartsWithNumber,它们返回一个布尔值,指示当前字符串实例是否分别以大写,小写和数字开头。
  • 在.NET Core中,如果字符是大写字符,则Char.IsUpper方法返回true;如果字符是小写字符,则Char.IsLower方法返回true;如果字符是数字字符,则Char.IsNumber方法返回true
  • 在菜单栏上,选择Build,Build Solution。 该项目应该编译没有错误。
  • .NET Core控制台项目无法访问这个类库。
  • 现在要使用这个类库,需要在控制台项目中添加这个类库的引用。

为此,展开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); 
      } 
   } 
}

现在运行应用程序,将看到以下输出。如下所示 -

为了更好的理解,在接下来的章节中也会涉及到如何在项目中使用类库的其他扩展方法。


上一篇:.Windows运行时和扩展SDK

下一篇:.NET Core可移植类库

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程