'Createanewinstanceofanobject.
DimobjFileAsNewFile
objFile.Path="C:AUTOEXEC.BAT"
'AddtoaCollectionobject.
colFiles.AddobjFile,objFile.ShortName
应用Collection类,应用程序调用该类的Add方法,传递任何必需的信息。请将先前的代码与Files类的Add方法做一比较:
WithaCollectionclass,theapplicationcallstheAddmethodoftheclass,passinganyrequiredinformation.ContrastthepreviouscodewiththeAddmethodoftheFilesclass:
PublicFunctionAdd(PathAsString)AsFile
DimobjFileAsFile
'CreatethenewFileobject.
SetobjFile=NewFile
objFile.Path=Path
'AddittothePrivatecollection.
pcolFiles.AddobjFile,objFile.ShortName
'Returnapointertothenewobject.
SetAdd=objFile
EndFunction
在本例中,到Collection的对象创建和添加发生在Add方法内部;而类则保留了完整的控制。任何必需的信息(例如文件的路径)是作为参数向方法提供的。由应用程序调用将文件添加到Collection的代码然后可以简化为:
'Addafiletothecollection.
colFiles.Add"C:AUTOEXEC.BAT"
InadditiontotheAddmethod,theCollectionclassshouldalsoimplementtheItemandRemovemethods,aswellasaCountproperty:
PublicFunctionItem(KeyAsVariant)AsFile
'Returnaniteminthecollection.
SetItem=pcolFiles.Item(Key)
EndFunction
PublicSubRemove(KeyAsVariant)
'Removeanitemfromthecollection.
pcolFiles.RemoveKey
EndSub
PropertyGetCount()AsLong
'Returnthenumberofitems.
Count=pcolFiles.Count
EndProperty
请注意,在这三种方法中,我们省略了错误处理--有些事情你是从来都不应该做的!至少应该包括一个错误处理器,通过使用Err对象的Raise方法来将错误传递、给调用过程。
图3这个表单通过显示文件信息来说明Collection类
'Privatevariabletostorepath.
PrivatepstrPathAsString
PropertyGetPath()AsString
'Returnstoredpathvalue.
Path=pstrPath
EndProperty
PropertyLetPath(strPathAsString)
DimstrFileAsString
'Clearthecollection.
SetpcolFiles=NewCollection
'Makesurethere'sabackslash.
IfRight(strPath,1)<>""Then
strPath=strPath&""
EndIf
'Getthefirstfile.
strFile=Dir(strPath&"*.*",_
vbReadOnlyOrvbHiddenOrvbArchiveOrvbSystem)
DoUntilLen(strFile)=0
'Addittothecollection.
CallAdd(strPath&strFile)
'Getthenextfile.
strFile=Dir()
Loop
'Savethepath.
pstrPath=strPath
EndProperty
图4向Collection类添加Path属性。将该属性和类设置为扫描目录并将所找到的每个文件添加到私有Collection对象。
【itbulo.com/post.php?action=newthread&fid=51&extra=page%3D1" title="如有错误,麻烦请及时告诉我们,谢谢。" target="_blank">我要纠错】【itbulo.com/" target="_blank">进入论坛交流】【关闭此页】【iTbulo.net/" class="lblue" target="_blank">进入博客】
扩展Collection类
现
【中国下载站】【设为主页】【收藏本页】【打印本文】【回到顶部】【关闭此页】