VB.Net中构造函数,和对象得创建
VB.Net使用一个称之为 New 得成员函数,该函数允许继承构造函数。
VB.Net一个很好的功能是重载的使用,对于提供构造函数来说是很理想的。New方法是重载的一个特殊例子,这是由于它并不要求Overloads关键字。例如下面一个Person类:
Public Class Person
Private _firstName as string
Private _lastName as string
Sub New()
_firstName=""
_lastName=""
End Sub
Sub New(firstName as String, lastName as String)
_firstName=firstName
_lastName=lastName
End Sub
Public Property FirstName() as string
'属性代码
End Property
Public Property LastName() as string
'属性代码
End Property
End Class
例子里面使用了两次Sub New,一次没有参数,一次有参数。所以我们可以这样:
Dim coolDude as New Person()
coolDude.FirstName="Vince"
coolDude.LastName="Patel"
或者
Dim coolDude as New Person( "Vince","Patel")
析构函数和对象析构
VB.Net里面析构函数如下:
Sub Destruct{}
End Sub
.Net里面析构函数的调用是围绕CLR来解决问题的。Garbage Collection(GC)是CLR的一个不错的功能,在后台运行,负责收集不在引用的的对象,使我们不再为析构这些对象引用而操心。但是,其缺点在于,由于他是一个后台任务,因此我们无法知道析构函数究竟在什么时候被调用。
MS发布了专门的用来说明无用单元收集及其效果的文件(查找MSDN中关于Deterministic Finalization的内容)。
如果对象不再使用的时候,需要确保某些必要的处理(如清除资源)。如果这也是个问题的话,就建议创建一个包含此功能的方法,并且在使用完实例时候,调用该方法。
由于无用单元回收器始终运行,所以释放对象和回收无用单元的差别很小。
引用
VS.Net里面引用装配件(甚至组件)有些类似,引用可以在项目管理器里面添加,也可以在代码中以关键字Imports来实现。
也可以使用别名引用:
Imports aliasName=Namespace
如果使用了别名,该别名就必须包含在对Namespace所包含的类的引用中。如:我们有一个称为MyComponent的Namespace(包含了一个MyClass类),就可以用下面这样导入该Namespace:
Imports foo=MyComponent
但是不能这样访问该类:
Dim comp as MyClass
因改使用一下语法:
Dim comp as foo.MyClass
用VB来构造链表
基本思想如下:
class ListElement '链节
public Next as ListElement
public Previois as ListElement
public MyList as LinkedList
public sub Remove()
if not isnothing(me.Next) then
Next.Previous = me.Previous
else
MyList.Last = me.Previous
end if
if not isnothing(me.Previous) then
...
else
...
end if
end sub
...
end class
class LinkedList '链表
public First as ListElement
public Last as ListElemebt
public sub Add(After as ListElement)
dim LE as new ListElement
LE.MyList = me
if isnothing(After) then
LE.Next = me.First
me.First.Previos = LE
me.First = LE
elseif isnothing(After.Next) then
...
else
LE.Previous = After
LE.Next = After.Next
After.Next = LE
LE.Next.Previous = LE
end if
end sub
...
end class
C#
构造函数
C#里面构造函数和VB.Net不同,使用相同名称的方法作为类,而不是为使用构造函数而使用类:
Public class person
{
Private string _firstName;
}
运算符的重载
C#支持运算符的重载,例子:
CNumber c1= new CNumber(12,4);
CNumber c2 = new CNumber(5,6);
当两数相加是,需要独立相加实数和虚数。可以用这个方法:
Pulic CNumber Add(CNumber c1,CNumber c2)
{
Return new CNumber(c1.real+c2.real,c1.imag+c2.imag)
}
然后调用
CNumber c3 = CNumber.Add(c1,c2);
上面的代码是对的的,不过我们可以采用更好的办法——重载运算符
Public static CNumber operator +(CNumber c1,CNumber c2);
{
Return new CNumber(c1.real+c2.real,c1.imag+c2.imag);
}
CNumber c3= c1+c2;