.NET核心 - 创建.NET标准库

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

  • 使用开发的类库.NET Core支持.NET标准库,它允许任何支持该版本.NET标准库的.NET平台调用您的库.

  • 完成类库后,您可以决定是将其作为第三方组件分发,还是将其作为与一个或多个应用程序捆绑在一起的组件包含在内.

让我们首先在Console应用程序中添加一个类库项目;右键单击解决方案资源管理器中的 src 文件夹,然后选择添加 → 新项目...

New Project

添加新项目对话框,选择.NET Core节点,然后选择类库(.NET Core)项目模板.

在"名称"文本框中输入"UtilityLibrary"作为项目的名称,如下图所示.

UtilityLibrary

单击"确定"以创建类库项目.创建项目后,让我们添加一个新类.在解决方案资源管理器中右键单击项目,然后选择添加 → 类...

Class

选择上课在中间窗格中,在名称和字段中输入StringLib.cs,然后单击添加.添加类后,再替换StringLib.cs文件中的以下代码.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
  
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); 
      } 
   } 
}


  • 班级library, UtilityLibrary.StringLib ,包含一些方法,如 StartsWithUpper StartsWithLower StartsWithNumber ,它们返回一个布尔值表示当前字符串实例是分别以大写,小写和数字开头.

  • 在.NET Core中, Char.IsUpper 方法返回true;如果字符是小写,则Char.IsLower方法返回true;如果字符是数字,则Char.IsNumber方法返回true.

  • 在菜单栏上,选择Build,Build Solution.该项目应该编译没有错误.

  • 我们的.NET Core控制台项目无法访问我们的类库.

  • 现在要使用这个类库,我们需要在控制台项目中添加这个类库的引用.

为此,展开FirstApp并右键单击References并选择添加引用...

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); 
      } 
   } 
}


现在让我们运行你的应用程序,你会看到以下输出.

Application

为了更好地理解,让我们使用其他扩展方法您项目中的类库.