Core基础 专题
您的位置:csharp > Core基础 专题 > .NET Core创建.NET标准库
.NET Core创建.NET标准库
作者:--    发布时间:2019-11-20

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

  • 使用.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); 
      } 
   } 
}

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

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


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册