您的位置:首页 > 编程语言 > C#

c#自定义 Class Library(类库)与Windows Form Control Library(控件库)的区别

2012-11-04 16:31 866 查看
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# 索引器的使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐