我们已经讨论了各种数据类型。 VB.Net中提供的基本值类型可以分为:
类型 | 示例 |
---|---|
Integral types | SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char |
Floating point types | Single and Double |
Decimal types | Decimal |
Boolean types | True or False values, as assigned |
Date types | Date |
VB.Net中的变量声明
Dim语句用于一个或多个变量的变量声明和存储分配。 Dim语句用于模块,类,结构,过程或块级别。
VB.Net中变量声明的语法是:
- [ < attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]
- [ ReadOnly ] Dim [ WithEvents ] variablelist
1、attributelist是适用于变量的属性列表。 可选的。
2、accessmodifier定义变量的访问级别,它具有值 - Public,Protected,Friend,Protected Friend和Private。 可选的。
3、Shared共享声明一个共享变量,它不与类或结构的任何特定实例相关联,而是可用于类或结构的所有实例。 可选的。
4、Shadows阴影表示变量在基类中重新声明和隐藏一个同名的元素或一组重载的元素。 可选的。
5、Static表示变量将保留其值,即使在声明它的过程终止之后。 可选的。
6、ReadOnly表示变量可以读取,但不能写入。 可选的。
7、WithEvents指定该变量用于响应分配给变量的实例引发的事件。 可选的。
8、Variablelist提供了声明的变量列表。
变量列表中的每个变量具有以下语法和部分:
- variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]
1、variablename:是变量的名称
2、boundslist:可选。 它提供了数组变量的每个维度的边界列表。
3、New:可选。 当Dim语句运行时,它创建一个类的新实例。
4、datatype:如果Option Strict为On,则为必需。 它指定变量的数据类型。
5、initializer:如果未指定New,则为可选。 创建时评估并分配给变量的表达式。
一些有效的变量声明及其定义如下所示:
- Dim StudentID As Integer
- Dim StudentName As String
- Dim Salary As Double
- Dim count1, count2 As Integer
- Dim status As Boolean
- Dim exitButton As New System.Windows.Forms.Button
- Dim lastTime, nextTime As Date
VB.Net中的变量初始化
变量被初始化(赋值)一个等号,然后是一个常量表达式。 初始化的一般形式是:
- variable_name = value;
例如,
- Dim pi As Double
- pi = 3.14159
您可以在声明时初始化变量,如下所示:
- Dim StudentID As Integer = 100
- Dim StudentName As String = "Bill Smith"
示例
尝试下面的例子,它使用各种类型的变量:
- Module variablesNdataypes
- Sub Main()
- Dim a As Short
- Dim b As Integer
- Dim c As Double
- a = 10
- b = 20
- c = a + b
- Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
- Console.ReadLine()
- End Sub
- End Module
当上述代码被编译和执行时,它产生了以下结果:
- a = 10, b = 20, c = 30
接受来自用户的值
System命名空间中的控制台类提供了一个函数ReadLine,用于接受来自用户的输入并将其存储到变量中。 例如,
- Dim message As String
- message = Console.ReadLine
下面的例子说明:
- Module variablesNdataypes
- Sub Main()
- Dim message As String
- Console.Write("Enter message: ")
- message = Console.ReadLine
- Console.WriteLine()
- Console.WriteLine("Your Message: {0}", message)
- Console.ReadLine()
- End Sub
- End Module
当上述代码被编译和执行时,它产生了以下结果(假设用户输入的Hello World):
- Enter message: Hello World
- Your Message: Hello World
Lvalues和Rvalues
有两种表达式:
- lvalue:作为左值的表达式可能出现在赋值的左侧或右侧。
- rvalue:作为右值的表达式可能出现在作业的右侧但不是左侧。
变量是左值,因此可能出现在作业的左侧。 数字文字是右值,因此可能不会分配,不能出现在左侧。 以下是有效的语句:
- Dim g As Integer = 20
但以下并不是有效的语句,并会生成编译时的错误:
- 20 = g
转载本站内容时,请务必注明来自W3xue,违者必究。