visual basic.net 讓 local 變數支援 block 範圍,也就是在迴圈或 if 等等區塊內宣告的變數在外部是看不到的,所以若程式碼撰寫如下
imports system
namespace mynamespace
module mymodule sub main() dim j as integer for j=1 to 10 if true then dim i as integer i=i+1 console.writeline("在內部的 i= " & cstr(i)) end if console.writeline("可否使用在內部的 i= " & cstr(i)) next j end sub
function getstringsfromfile(byval filename as string) as string dim strtest, strings as string dim stream as streamreader = file.opentext(filename) 開啟檔案
try while true 迴圈一直執行到 endofstreamexception 錯誤發生 strtest = stream.readline() if strtest = "" then throw new endofstreamexception end if strings = strings + strtest end while
catch eofexcep as endofstreamexception
不需要做任何事,已經達到檔案結尾
catch ioexcep as ioexception
有一些錯誤發生了,回報錯誤的發生 msgbox(ioexcep.message) strings = nothing
finally stream.close() 關閉檔案 end try return strings
end function
使用正確的資料型別
在定義 subroutines 和 functions 時,可以利用 vb 提供的資料型別來定義參數,以及 function 回傳的型別
sub dosomething(byval strvalue1 as string, byval intcount as integer, byref strvalue2 as string = "初始內容")
function dosomething(byval strvalue1 as string, byval intcount as integer, byref strvalue2 as string = "初始內容") as string
function dosomething(byval strvalue1 as string, byval intcount as integer, byref strvalue2 as string = "初始內容" _ optional byval strtype = "預設內容" as string) as string