国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > VBScript > 正文

VBS類構造函數與Default關鍵字使用介紹

2020-06-26 18:28:07
字體:
來源:轉載
供稿:網友
很多人并不知道 VBS 中還有個 Default 關鍵字,更不用說知道 Default 關鍵字的用法。
 
其實 MSDN 的 VBScript 文檔中關于 Function 和 Sub 語句的部分提到過 Default 關鍵字: 
復制代碼代碼如下:

Default 
Used only with the Public keyword in a Class block to indicate that the Function procedure is the default method for the class. An error occurs if more than one Default procedure is specified in a class. 

Default 只能在 Class 語句塊中與 Public 關鍵字一起使用來表明函數過程是類的默認方法。如果類中一個以上的過程被定義為 Default,那么會出現錯誤。 
一個簡單的例子: 
復制代碼代碼如下:

Class MyClass 
Public Default Function SayHello(name) 
SayHello = "Hello, " & name 
End Function 
End Class 
Set o = New MyClass 
MsgBox o("demon") 

很多面向對象的語言都能使用構造函數來初始化類的對象,但是 VBS 卻沒有構造函數的概念,只是提供了一個類初始化事件來初始化對象: 
復制代碼代碼如下:

Class TestClass 
' Setup Initialize event. 
Private Sub Class_Initialize 
MsgBox("TestClass started") 
End Sub 
' Setup Terminate event. 
Private Sub Class_Terminate 
MsgBox("TestClass terminated") 
End Sub 
End Class 
' Create an instance of TestClass. 
Set X = New TestClass 
' Destroy the instance. 
Set X = Nothing 

雖然看起來很像構造函數,但是卻不能帶參數,沒有辦法像其他語言那樣用特定的參數來初始化對象。 
有了 Default 關鍵字之后,我們可以模擬實現構造函數的功能: 
復制代碼代碼如下:

'Author: Demon 
'Date: 2011/09/29 
'Website: http://demon.tw 
Class Rectangle 
Private height, width 
Public Default Function Construtor(h, w) 
height = h : width = w 
Set Construtor = Me 
End Function 
Public Property Get Area 
Area = height * width 
End Property 
End Class 
'看起來是不是很像構造函數呢 
Set r = (New Rectangle)(6, 8) 
MsgBox r.Area 

參考鏈接:VBScript's default keyword
原文:http://demon.tw/programming/vbs-default-keyword.html


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 共和县| 健康| 钟山县| 富锦市| 黔西县| 革吉县| 靖边县| 阿拉尔市| 化德县| 扎兰屯市| 习水县| 安乡县| 呈贡县| 襄樊市| 昭苏县| 阳高县| 三明市| 岳阳县| 丹寨县| 太湖县| 布拖县| 郧西县| 濮阳县| 平邑县| 聂荣县| 潜江市| 锦屏县| 阳东县| 湛江市| 林州市| 榆树市| 兴海县| 庄浪县| 阿瓦提县| 天气| 瓦房店市| 洛浦县| 仁寿县| 塘沽区| 苗栗县| 廉江市|