C#类库使用技巧

时间:2022-07-23
本文章向大家介绍C#类库使用技巧,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

第一步:新建类库testClass

然后添加两个类 class1和class2

class1添加代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testClass1
{
    public class Class1
    {
        public int sumd(int a,int b)
        {
            return a + b;

        }
    }
}

class2添加代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testClass2
{
    public class Class2
    {
        public int multiply(int a, int b)
        {
            return a * b;

        }
    }
}

然后点击 --生成

dll库就生成完毕了!

接下来在新工程中引用这个dll

然后:

using testClass1;

using testClass2;

具体代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using testClass1;
using testClass2;

namespace WindowsFormsApp24
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 cs1 = new Class1();
            richTextBox1.Text = cs1.sumd(10, 20).ToString();

            Class2 cs2 = new Class2();
            richTextBox2.Text = cs2.multiply(10, 20).ToString();


        }
    }
}

运行结果如下:

remark:-. dll引用后,如果类库工程路径没有发生变更,在工程中点击F12依然能定位到源代码!

-. 类库重新生成后,调用类库的项目也会跟着变更,不用重新引用!