创建一个类MyComponentTest
/************************************************************************* * 创建人:Devilhand * 创建时间:2010-9-11 * 说明:组件的编写 *************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace MyComponent { public class MyComponentTest { private string[] stringSet; public event EventHandler Modified;//声明一个事件 //获取字符串数组的长度 public int StringSetLength { get { return stringSet.Length; } } public MyComponentTest() { stringSet = new string[] { "张三", "李四", "王五" }; } //获取指定索引的字符串数组元素的值 public string GetString(int index) { if (0 > index || stringSet.Length <= index) { throw new MyApplicationException("索引超出范围"); } return stringSet[index]; } //修改指定索引的字符串数组元素的值 public void Modify(int index, string value) { if (0 > index || stringSet.Length <= index) { throw new MyApplicationException("索引超出范围"); } stringSet[index] = value; OnModify();//触发事件 } //调用这个方法触发事件 private void OnModify() { EventArgs e = new EventArgs(); if (null != Modified) { Modified(this, e); } } } //自定义异常处理类 public class MyApplicationException : ApplicationException { public MyApplicationException() { } public MyApplicationException(string message) : base(message) { } public MyApplicationException(string message, Exception e) : base(message, e) { } } }
使用Visual Studio 2005命令提示把类MyComponentTest编译成dll文件(转到类MyComponentTest所在目录,运行下面代码)
csc /target:library MyComponentTest.cs
组件的使用(先添加MyComponentTest.dll的引用)
MyComponent.MyComponentTest component; public Form1() { InitializeComponent(); component = new MyComponentTest(); component.Modified += new EventHandler(DoWork); } //更新字符串数组 private void button1_Click(object sender, EventArgs e) { try { component.Modify(Convert.ToInt32(textBox1.Text.Trim()), textBox2.Text.Trim()); } catch (MyApplicationException me) { MessageBox.Show ( me.Message); } } //判断字符串数组更新是否成功 private void DoWork(object sender, EventArgs e) { if (component.GetString(Convert.ToInt32(textBox1.Text.Trim()))==textBox2.Text .Trim ()) { MessageBox.Show("修改成功!"); } } //获取字符串数组的元素 private void button2_Click(object sender, EventArgs e) { try { MessageBox.Show(component.GetString(Convert.ToInt32(textBox3.Text.Trim()))); } catch (MyApplicationException me) { MessageBox.Show(me.Message); } }