开发学院

您的位置:首页>教程>正文

教程正文

.NET Core 创建.NET标准库

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

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

  当你完成类库时,你可以决定是否要将它作为第三方组件分发,或者是否要将它作为一个与一个或多个应用程序捆绑在一起的组件。

  让我们从在控制台应用程序中添加类库项目开始;右键单击解决方案资源管理器中的解决方案文件名,然后选择添加→新建项目…

001_add_project.jpg

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

  在“名称”文本框中,输入UtilityLibrary作为项目名称,如下图所示。

002_chooice_type.jpg

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

003_create_class.jpg

  在中间窗格中选择类,在名称字段中输入StringLib.cs,然后单击添加。

004_create_class2.jpg

  一旦添加好了类,用以下代码替换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); 
      } 
   } 
}

  UtilityLibrary.StringLib中包含一些方法,例如StartsWithLower、StartsWithLower和StartsWithNumber,它们返回一个布尔值,指示当前字符串实例是否分别以大写、小写和数字开头。

  在.NET Core中,Char.IsUpper方法如果字符大写,则返回true,Char.IsLower方法在字符为小写时返回true,类似的还有Char.IsNumber,IsNumber方法返回true。

  在菜单栏上,选择构建,构建解决方案。这个项目应该没有错误地编译。

  我们的.NET Core控制台项目目前无法直接访问我们新创建的类库。

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

  为此,展开FirstApp,右键单击依赖项并选择添加引用…

  在引用管理器对话框中,选择UtilityLibrary,然后单击“确定”。

005_add_ref.jpg

  现在让我们打开控制台项目的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); 
      } 
   } 
}

  现在运行应用程序,您将看到以下输出。

006_application.jpg

  为了更好地理解,我们也可以在项目中测试类库的其他扩展方法。