類型
Basic4android的類型系統是直接從Java的類型系統中派生的.
有兩種類型的變量: 基本類型 and 非基本類型.
基本類型包括數字類型: Byte, Short, Int, Long, Float 和 Double.
基本類型也包括: Boolean 和 Char.
類型及范圍列表: http://www.basic4ppc.com/forum/basic...html#post45511
但函數調用或者賦值時,基本類型總是直接把值傳遞過去.
例如:
Sub S1
Dim A As Int
A = 12
S2(A) Log(A) 'Prints 12
End Sub
Sub S2(B As Int)
B = 45
End Sub
其他所有的類型,,包括基本類型數組和字符串都被歸入到非基本類型.
當你將一個非基本類型傳遞給函數或者給它賦另外一個不同的值時,會將其的引用復制一份傳遞過去 .
這意味着數據的本身沒有被復制.
這與直接把引用傳遞過去有點小小不同,因為你不能改變原始變量的引用.
所有的類型都可以被看作是對象.
像lists 和 maps這樣的容器工作原理與對象相似,因此可以保存任何值.
下面是一個常見的錯誤例子, 在這里,開發者試圖向列表里面加入幾個數組:
Dim arr(3) As Int
Dim List1 As List
List1.Initialize
For i = 1 To 5
arr(0) = i * 2
arr(1) = i * 2
arr(2) = i * 2
List1.Add(arr) 'Add the whole array as a single item
Next
arr = List1.Get(0) 'get the first item from the list
Log(arr(0)) 'What will be printed here???
本來希望能夠打印出來2. 但是結果確是10.
我們建立了一個數組,並在列表里面加了這個數組的5個引用.
這個數組最后的值在最后的一個循環里面被改為10,因此出錯了
要改正這個錯誤,我們需要在每一個循環里面產生一個新的數組.
這一在每次循環里面調用Dim:
Dim arr(3) As Int 'This?call?is?redundant?in?this?case.在這個例子里面,這一句是多余的
Dim List1 As List
List1.Initialize
For i = 1 To 5 Dim arr(3) As Int
arr(0) = i * 2 arr(1) = i * 2
arr(2) = i * 2
List1.Add(arr) 'Add the whole array as a single item
Next
arr = List1.Get(0) 'get the first item from the list
Log(arr(0)) 'Will print 2
小貼士: 你可以使用 agraham的 CollectionsExtra 庫來復制數組.
轉換
Basic4android 當需要時會自動轉換類型的. 它也可以自動的將數字轉換為字符串,反之亦然.
在很多情況下,你需要顯式的轉換一個對象成另外一個特定的類型.
這可以通過將一個對象賦值給一個需要類型的變量.
例如, Sender 關鍵字返回觸發這個事件的對象.
下面的代碼改變按鈕的顏色. 注意有好幾個按鈕共享同一個事件子程.
Sub Globals
Dim Btn1, Btn2, Btn3 As Button
End Sub
Sub Activity_Create(FirstTime As Boolean)
Btn1.Initialize("Btn")
Btn2.Initialize("Btn")
Btn3.Initialize("Btn") Activity.AddView(Btn1, 10dip, 10dip, 200dip, 50dip)
Activity.AddView(Btn2, 10dip, 70dip, 200dip, 50dip)
Activity.AddView(Btn3, 10dip, 130dip, 200dip, 50dip)
End Sub
Sub Btn_Click
Dim b As Button
b = Sender 'Cast the Object to Button
b.Color?=?Colors.RGB(Rnd(0, 255), Rnd(0, 255), Rnd(0, 255))
End Sub
上面的代碼也可以寫的更優雅點:
Sub Globals
End Sub
Sub Activity_Create(FirstTime As Boolean)
For i = 0 To 9 'create 10 buttons
Dim Btn As Button Btn.Initialize("Btn")
Activity.AddView(Btn, 10dip, 10dip + 60dip * i, 200dip, 50dip)
Next
End Sub
Sub Btn_Click
Dim b As Button
b = Sender
b.Color = Colors.RGB(Rnd(0, 255), Rnd(0, 255), Rnd(0, 255))
End Sub
范圍
在Sub Globals or Sub Process_Globals 里面定義的變量可以在所有的子程里面訪問.
其他的變量是局部的,只能在定義其的子程里面訪問.
請參見 Activity lifecycle tutorial 來了解Globals和Process_Globals變量的區別.
提示
所有的views類型可以看成是Views. 這樣就可以方便的改變views的公共屬性.
例如,下面的代碼使 activity的所有直系子view 不可用:
For i = 0 To Activity.NumberOfViews - 1
Dim v As View
v = Activity.GetView(i)
v.Enabled = False
Next
如果們僅僅想使按鈕不可用:
For i = 0 To Activity.NumberOfViews - 1
Dim v As View
v = Activity.GetView(i)
If v Is Button Then 'check whether it is a Button
v.Enabled = False
End If
Next
Type 關鍵字讓你可以建立自己的對象類型. 自定義類型的操作方式與其他非基本類型的操作方式一樣.