使用C#轻松编写.Net组件

 

在.net框架提出之前,编写组件被视为是一种需要高深技巧的工作,令很多人望而生畏。而.net的出现,使得组件的编写变得如此平易近人,而.net framework的核心语言C#,更是被称为面向组件的语言。在这里,我将向大家介绍如何使用C#编写在.net framework环境下运行的组件,包括如何编写组件类,如何添加域、属性以及事件,如何编译和分发组件。

首先看下面这段足够简单的代码实例(在后面我们将慢慢将它变成一个五脏俱全的组件):

using System;
namespace ComponentCS
{
public class StringComponent
{
private string[] StringsSet;
public int StringLength
{
get
{
return StringsSet.Length;
}
}
public void Modify(int index,string value)
{
if ((index 〈 0) || (index 〉= StringsSet.Length))
{
throw new IndexOutOfRangeException();
}
else
{
StringsSet[index]=value;
OnModify();
}
}
public StringComponent()
{
StringsSet = new string[]
{
"C# String 0",
"C# String 1",
"C# String 2",
"C# String 3"
};
}
public string GetString(int index)
{
if ((index 〈 0) || (index 〉= StringsSet.Length))
{
throw new IndexOutOfRangeException();
}
return StringsSet[index];
}
}
}

一般地,我们首先创建一个命名空间(namespace)用来封装这个组件中一系列的类:

namespace CompCS

命名空间的使用非常灵活,它可以被嵌套,也可以将其内部的类分别写在多个文件中,相应地,还可以在一个源文件中声明多个非嵌套的命名空间。下面是一个使用嵌套的命名空间的示例代码:

namespace NestIt

{ namespace NestedNameSpace { class myClass

{ public static void DoSth() { ... } } }}

你可以这样引用类myClass:

NestIt.NestedNameSpace.myClass.DoSth();

还是回到我们的命名空间CompCS,我们使用下面的语句声明了一个类StringComponent:

public class StringComponent

命名空间中的类是必需的,因为C#所有的代码都必须封装在一个个类中,所以没有类的命名空间没有任何价值。下面我们为这个类添加一个公共(public)域:

private string[] StringsSet;

此外,它还可能需要定义一些属性,下面是定义一个只读的属性的例子:

public int StringLength{ get { return StringsSet.Length; }}

C#中的属性更充分地体现了对象的封装性,不直接操作类的数据内容而是通过访问器进行访问,它借助于get 和set访问器对属性的值进行读写。而在C++中,这是需要程序员手工完成的一项工作。

在属性的访问声明中:

◆只有set 访问器表明属性的值只能进行设置而不能读出
◆只有get 访问器表明属性的值是只读的不能改写
◆同时具有set 访问器和get 访问器表明属性的值的读写都是允许的

你或许会发现域和属性是如此相似,确实属性和域的语法比较类似的,但是它们是绝对不同的,区别在于你不能把属性当做变量那样使用,也不能把属性作为引用型参数或输出参数来进行传递,相反的,对于域,没有这些限制。

下面的代码定义了这个类的构造函数:

public StringComponent()

构造函数必须与类同名,它可以重载,但是不能有返回值,因此它也没有返回值类型前缀。当用户新建一个类的实例时,构造函数就会自动执行,同时,C#的垃圾收集机制开始对这个实例进行管理,并且将在适当的时候回收资源。

然后,我们编写了一个GetString()函数,这个函数根据用户传入的index值,返回相应的记录:

public string GetString(int index)
{ … return StringsSet[index];}

要注意的是其中的异常处理的方法:

throw new IndexOutOfRangeException();

作为一个健壮的组件,异常处理机制是不可或缺的,虽然它可能会消耗掉一些资源,但是它带来的安全性的提升会使你觉得消耗的资源简直微不足道。这里使用了一个系统定义的异常类IndexOutOfRangeException(),事实上,更多的情况是你必须自己定义异常类,以适应各种不同的情况。下面的代码示例展示了如何定义一个异常类:

public class MyApplicationException : ApplicationException{ public string AMsg;
public MyApplicatonException(string strMsg)
{
AMsg=strMsg;
}
}

定义一个异常类与定义普通的类并没有什么区别,唯一的区别在于异常类必须继承自System.Exception类。事实上,微软公司推荐把所有用户自定义的异常类作为ApplicationException类的子类。把类MyApplicationException放到命名空间CompCS中,这样你就可以改写GetString()函数中的异常处理方式。下面是一个带有更完善的异常处理机制的GetString()方法:

public string GetString(int index) { try { if ((index 〈 0) || (index 〉= StringsSet.Length))

{ throw new MyApplicationException("参数超出范围"); } } catch(MyApplicationException mErr)

{ Console.WriteLine(mErr.AMsg); } catch(Exception Err) { Console.WriteLine(Err.Message); }
return StringsSet[index];
}

采用类似这样的方式,你可以应付比这复杂得多的情况。

下面,我们来考虑给这个类添加事件。事件机制的引入使得开发者可以更灵活地开发程序。下面的代码示例展示了如何定义一个事件:

public event EventHandler Modified;

在C#中使用event关键字定义事件。把这个定义放到我们的类ComponentCS.StringComponent中,然后我们添加一个函数Modify(),这个函数修改字符数组StringsSet中指定位置的值,同时引发OnModify事件,而在Modify事件中,我们调用的是事件Modified所指定的函数:

public void Modify(int index,string value)

{ if ((index 〈 0) || (index 〉= StringsSet.Length))

{ throw new IndexOutOfRangeException(); }

else { StringsSet[index]=value; OnModify(); } }
private void OnModify()
{
EventArgs e=new EventArgs();
if(!(Modified==null))
Modified(this,e);
}

然后我们可以用如下的方法调用:

private void DoIt(){ StringComponent mysc=new StringComponent();

mysc.Modified+=new EventHandler(Called);

mysc.Modify(2,"another string");}

public void Called(object o,EventArgs e)

{ Console.WriteLine("Changed");}

在函数DoIt()中,我们首先建立了一个StringComponent类的对象mysc,然后将它的Mofidied事件关联到Called()方法:

mysc.Modified+=new EventHandler(Called);

注意“+=”符号的使用,相反地,如果使用“-=”符号,可以取消这个事件的绑定。

现在我们得到了一个虽然简单,但是比较完整的组件类:

using System;
namespace ComponentCS
{
public class StringComponent
{

private string[] StringsSet;
public event EventHandler Modified;
public int StringLength
{
get
{
return StringsSet.Length;
}
}
public void Modify(int index,string value)
{
if ((index 〈 0) || (index 〉= StringsSet.Length))
{
throw new IndexOutOfRangeException();
}
else
{
StringsSet[index]=value;
OnModify();
}
}
private void OnModify()
{
EventArgs e=new EventArgs();
if(!(Modified==null))
Modified(this,e);
}
public StringComponent()
{
StringsSet = new string[]
{
"C# String 0",
"C# String 1",
"C# String 2",
"C# String 3"
};
}
public string GetString(int index)
{
if ((index 〈 0) || (index 〉= StringsSet.Length))
{
throw new IndexOutOfRangeException();
}
return StringsSet[index];
}
}
}

最后要做的就是把它编译成.dll(动态链接库)文件,以便发布。发布成.dll文件最大的好处就是.dll文件中的内容已经编译,可以大大加快程序运行速度,此外还可以保护源代码。

将产生的.cs文件编译成为.dll文件的方法如下:

csc.exe /t:library /debug+ /out:myCom.dll example.cs

这样就输出了名为myCom.dll的.dll文件。

OK,我们已经完成一个组件,麻雀虽小,五脏俱全,这就是一切组件的基础了,整个过程花不了十分钟。

当然,如果是一个具备实际使用价值的组件,我们要考虑的远远不止这些,但是可以看到,C#对组件的强大支持,可以大大提高我们的开发效率,从而使我们有更多的精力放在算法设计等方面,开发出更加出色的组件

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/] Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值