Visual Studio创建自己的.dll文件,并且在其它项目中使用该.dll文件

1.简介

看了一些代码,发现直接用类名.方法名就调用了方法,但是点进方法查看,却发现没有方法体,但是功能却有,很奇怪。

后来才知道是在项目中添加了自己.dll文件的引用,然后再代码中引入了命名空间,然后直接可以调用了。具体操作如下。

2.首先用 Visual Studio创建一个类库项目

这个类库项目就是用于生成自己的.dll文件。

项目名是该项目的名字,也是生成.dll文件的名字,也是其它项目要引入的命名空间。

其中一个类的内容如下:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Show
{
    public class MyClass
    {
        /// <summary>
        /// 查找 table 的前两个字段你的信息
        /// </summary>
        /// <param name="table">表名</param>
        /// <returns>返回查询到的信息</returns>
        public static String ShowTable(String table) {
            String sqllj = "Data Source=.;Initial Catalog=liuyan;Integrated Security=True";
            SqlConnection con = new SqlConnection(sqllj);
            con.Open();
            String sqls = "SELECT * FROM ["+table+"]";
            SqlCommand sqlcmd = new SqlCommand(sqls, con);
            SqlDataReader reader = sqlcmd.ExecuteReader();
            String s = "";
            while (reader.Read()) {
                String s1 = reader.GetString(0);
                String s2 = reader.GetString(1);
                s += s1 + "  " + s2 + "\n";
            }
            reader.Close();
            con.Close();
            return s;
        }

    }

}

点击生成,并产生了一个.dll文件,这就是我们要用的,你可以把这个文件移动到任意位置。

3.新建一个窗体应用项目,并使用之前的.dll文件

①先添加项目对该.dll的引用

在要使用的地方引入命名空间   using Show;

然后再代码中直接使用即可:

            String s = MyClass.ShowTable("user");
            MessageBox.Show(s);

具体代码如下:

using Show;  //这里引入命名空间
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp1 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            init("");
        }

        private void init(String path) {
            String s = MyClass.ShowTable("user"); //直接使用
            MessageBox.Show(s);
        }

    }
}

在代码中中点进ShowTable方法查看,就会发现只有方法名而没有方法体。

注意点:

刚发现在类库项目中方法的注释信息,而在应用项目中点进方法却看不到了,是因为类库生成时候没有带上xml文档。

设置如下:

在类库项目中设置,右击项目,属性,生成中找到xml打勾,并重新生成.dll。

之后在应用项目,点进去方法,会发现,注释信息有了。

猜你喜欢

转载自blog.csdn.net/qq_38261174/article/details/84999212
今日推荐