c# 自定义类库与自定义控件

来源:互联网 发布:mac充电器灯不亮 编辑:程序博客网 时间:2024/05/16 18:10

Class Library(类库)与Windows Form Control Library(控件库)的区别:

两者编译都生成dll文件,不过控件库是特殊的类库。控件库可以编译运行,而类库只能编译,必须在其它可做为”Start up project”的工程中引用后使用。

引用类库的方法:在Solution Explorer中,工程的References上点右键,选择”Add reference”,然后选择browse找到相应的DLL添加

使用自定义控件库的方法:在Toolbox上单击右键,选择“choose items”,弹出对话框里点”Browse”,找到控件库添加。添加成功后,会在Toolbox的最下面出现自定义的控件。

创建自己的类库

参见:http://hi.baidu.com/hongyueer/blog/item/ce3b39a618133e92d143582d.html

1、新建工程 ,选择Class Library类型。

2、选择名字空间名。

3、创建自己的公用类。代码如下:

using System;

using System.Collections.Generic;

using System.Text;

 

namespace Chapter09

{

    public class Box

    {

        private string[] names ={ "length", "width", "height" };

        private double[] dimensions = new double[3];

        public Box(double length, double width, double height)

        {

            dimensions[0] = length;

            dimensions[1] = width;

            dimensions[2] = height;

        }

        public double this[int index]

        {

            get

            {

                if ((index < 0) || (index >= dimensions.Length))

                    return -1;

                else

                    return dimensions[index];

            }

            set

            {

                if (index >= 0 && index < dimensions.Length)

                    dimensions[index] = value;

            }

        }

 

        public double this[string name]

        {

            get

            {

                int i = 0;

                while ((i < names.Length) && (name.ToLower() != names[i]))

                    i++;

                return (i == names.Length) ? -1 : dimensions[i];

            }

            set

            {

                int i = 0;

                while ((i < names.Length) && (name.ToLower() != names[i]))

                    i++;

                if (i != names.Length)

                    dimensions[i] = value;

            }

        }

    }

}

5、测试自己的类库

首先增加对自己的类库的引用,(新建项目,在项目上右键-》添加引用,选择“浏览”标签,然后找到自己的dll文件,加入。)

然后用using包含自己的名字空间,即可使用自己的类了。代码如下:

using System;

using System.Collections.Generic;

using System.Text;

using Chapter09;

 

namespace Test_classLib

{

    class Program

    {

        static void Main(string[] args)

        {

            Box box = new Box(20, 30, 40);

 

            Console.WriteLine("Created a box :");

            Console.WriteLine("box[0]={0}", box[0]);

            Console.WriteLine("box[1]={0}", box[1]);

            Console.WriteLine("box[0]={0}", box["length"]);

            Console.WriteLine("box[\"width\"] = {0}", box["width"]);

        }

    }

}

说明:本例同时示例了C# 索引器的使用

原创粉丝点击