Visual Basic 入门教程笔记
下面是一个全面的 Visual Basic (VB) 教程,适合初学者和有一定编程经验的人士。Visual Basic 是一种由微软开发的高级编程语言,广泛用于 Windows 应用程序开发、Web 应用程序开发(如 ASP.NET)等。
1. 简介
- 定义:Visual Basic 是一种现代的、面向对象的编程语言,是 .NET 平台的一部分。
- 用途:
- Windows 桌面应用程序开发。
- Web 应用程序开发(如 ASP.NET)。
- 移动应用开发(如 Xamarin)。
- 企业级应用开发。
- 特点:
- 语法简洁清晰。
- 支持面向对象编程。
- 自动垃圾回收。
- 丰富的标准库。
- 跨平台支持(通过 .NET Core 和 .NET 5+)。
2. 安装 Visual Studio
在 Windows 上安装
- 访问 Visual Studio 官方网站 下载并安装最新版本的 Visual Studio。
- 在安装过程中,选择“ASP.NET 和 Web 开发”或“.NET 桌面开发”工作负载。
3. 第一个 Visual Basic 程序
创建项目目录
- 打开 Visual Studio 并创建一个新的控制台应用程序项目。
- 选择 “File” -> “New” -> “Project”。
- 选择 “Console App (.NET Core)” 或 “Console App (.NET Framework)”,然后点击 “Next”。
- 输入项目名称(例如
HelloWorld
),选择项目位置,然后点击 “Create”。
编写第一个程序
- 在
Module1.vb
文件中,你会看到以下代码:Module Module1 Sub Main() Console.WriteLine("Hello, World!") End Sub End Module
运行程序
- 点击工具栏上的“Start”按钮(绿色三角形)或按
F5
键来运行程序。 - 你应该会看到输出
Hello, World!
。
4. Visual Basic 基础语法
注释
- 单行注释使用
'
。 - 多行注释使用
''' ... '''
。
' 这是单行注释
'''
这是多行注释
可以跨越多行
'''
变量
- 变量需要显式声明类型。
- 支持隐式类型推断(使用
Dim
关键字)。
Dim a As Integer = 42
Dim b As Double = 3.14
Dim c As Boolean = True
Dim d As String = "Hello, World!"
Dim e = 10 ' e 的类型为 Integer
Dim f = "Hello" ' f 的类型为 String
数据类型
- 基本类型:
Integer
,Double
,Boolean
,Char
,String
。 - 复合类型:
Array
,List
,Dictionary
。
Dim myInt As Integer = 42
Dim myDouble As Double = 3.14
Dim myBool As Boolean = True
Dim myString As String = "Hello, World!"
Dim myArray(2) As Integer
myArray(0) = 1
myArray(1) = 2
myArray(2) = 3
Dim myList As New List(Of Integer) From {1, 2, 3}
Dim myDict As New Dictionary(Of String, Integer) From {
{"one", 1},
{"two", 2}
}
字符串
- 使用双引号
"
定义字符串。 - 字符串插值使用
$
符号。
Dim s1 As String = "Hello, World!"
Dim name As String = "Alice"
Dim s2 As String = $"Hello, {name}!"
控制结构
条件语句
If...Else
语句
Dim age As Integer = 18
If age >= 18 Then
Console.WriteLine("You are an adult.")
Else
Console.WriteLine("You are a minor.")
End If
循环
For
循环
For i As Integer = 0 To 4
Console.WriteLine(i) ' 输出: 0 1 2 3 4
Next
While
循环
Dim i As Integer = 0
While i < 5
Console.WriteLine(i) ' 输出: 0 1 2 3 4
i += 1
End While
ForEach
循环
Dim numbers() As Integer = {1, 2, 3}
For Each number As Integer In numbers
Console.WriteLine(number) ' 输出: 1 2 3
Next
5. 函数和子过程
定义函数
- 使用
Function
关键字定义有返回值的函数。 - 使用
Sub
关键字定义无返回值的过程。
Module Module1
Sub Main()
Dim result As String = Greet("Alice")
Console.WriteLine(result) ' 输出: Hello, Alice!
End Sub
Function Greet(name As String) As String
Return $"Hello, {name}!"
End Function
End Module
默认参数
- 函数可以有默认参数值。
Module Module1
Sub Main()
Dim result1 As String = Greet("Alice") ' 使用默认问候语
Dim result2 As String = Greet("Bob", "Hi there") ' 使用自定义问候语
Console.WriteLine(result1) ' 输出: Hello, Alice!
Console.WriteLine(result2) ' 输出: Hi there, Bob!
End Sub
Function Greet(name As String, Optional greeting As String = "Hello") As String
Return $"{greeting}, {name}!"
End Function
End Module
可变参数
- 使用
ParamArray
关键字定义可变参数。
Module Module1
Sub Main()
Dim sum As Integer = Sum(1, 2, 3, 4)
Console.WriteLine(sum) ' 输出: 10
End Sub
Function Sum(ParamArray numbers() As Integer) As Integer
Dim total As Integer = 0
For Each number As Integer In numbers
total += number
Next
Return total
End Function
End Module
6. 类和对象
定义类
- 使用
Class
关键字定义类。
Module Module1
Class Person
Public Property Name As String
Public Property Age As Integer
Public Sub New(name As String, age As Integer)
Me.Name = name
Me.Age = age
End Sub
Public Sub SayHello()
Console.WriteLine($"Hello, my name is {Me.Name} and I am {Me.Age} years old.")
End Sub
End Class
Sub Main()
Dim p As New Person("Alice", 30)
p.SayHello() ' 输出: Hello, my name is Alice and I am 30 years old.
End Sub
End Module
继承
- 使用
Inherits
关键字定义子类,并使用MyBase
关键字调用父类的方法。
Module Module1
Class Student
Inherits Person
Public Property Grade As String
Public Sub New(name As String, age As Integer, grade As String)
MyBase.New(name, age)
Me.Grade = grade
End Sub
Public Shadows Sub SayHello()
Console.WriteLine($"Hello, I'm a student named {Me.Name} and I am {Me.Age} years old, in grade {Me.Grade}.")
End Sub
End Class
Sub Main()
Dim s As New Student("Bob", 20, "A")
s.SayHello() ' 输出: Hello, I'm a student named Bob and I am 20 years old, in grade A.
End Sub
End Module
7. 文件操作
读取文件
- 使用
System.IO
命名空间中的StreamReader
读取文件。
Imports System.IO
Module Module1
Sub Main()
Dim filePath As String = "example.txt"
Try
Using reader As New StreamReader(filePath)
Dim content As String = reader.ReadToEnd()
Console.WriteLine(content)
End Using
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
写入文件
- 使用
System.IO
命名空间中的StreamWriter
写入文件。
Imports System.IO
Module Module1
Sub Main()
Dim filePath As String = "example.txt"
Try
Using writer As New StreamWriter(filePath)
writer.WriteLine("This is some text.")
End Using
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
追加内容
- 使用
System.IO
命名空间中的StreamWriter
以追加模式写入文件。
Imports System.IO
Module Module1
Sub Main()
Dim filePath As String = "example.txt"
Try
Using writer As New StreamWriter(filePath, append:=True)
writer.WriteLine(vbCrLf & "This is additional text.")
End Using
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
8. 异常处理
捕获异常
- 使用
Try...Catch
语句捕获和处理异常。
Module Module1
Sub Main()
Try
Dim result As Integer = Divide(10, 0)
Console.WriteLine(result)
Catch ex As DivideByZeroException
Console.WriteLine($"Error: {ex.Message}")
Catch ex As Exception
Console.WriteLine($"An unexpected error occurred: {ex.Message}")
End Try
End Sub
Function Divide(a As Integer, b As Integer) As Integer
If b = 0 Then
Throw New DivideByZeroException("Cannot divide by zero.")
End If
Return a \ b
End Function
End Module
抛出异常
- 使用
Throw
关键字抛出异常。
Module Module1
Sub Main()
Try
Dim result As Integer = Divide(10, 0)
Console.WriteLine(result)
Catch ex As DivideByZeroException
Console.WriteLine($"Error: {ex.Message}")
End Try
End Sub
Function Divide(a As Integer, b As Integer) As Integer
If b = 0 Then
Throw New DivideByZeroException("Cannot divide by zero.")
End If
Return a \ b
End Function
End Module
9. 标准库
数学运算
- 使用
System
命名空间中的Math
类进行数学运算。
Imports System
Module Module1
Sub Main()
Dim squareRoot As Double = Math.Sqrt(16)
Dim pi As Double = Math.PI
Console.WriteLine($"Square root of 16: {squareRoot}") ' 输出: 4.0
Console.WriteLine($"Pi: {pi}") ' 输出: 3.141592653589793
End Sub
End Module
时间和日期
- 使用
System
命名空间中的DateTime
类处理时间和日期。
Imports System
Module Module1
Sub Main()
Dim now As DateTime = DateTime.Now
Console.WriteLine(now) ' 输出当前时间
End Sub
End Module
随机数
- 使用
System
命名空间中的Random
类生成随机数。
Imports System
Module Module1
Sub Main()
Dim random As New Random()
Dim randomNumber As Integer = random.Next(1, 11) ' 生成 1 到 10 之间的随机整数
Console.WriteLine(randomNumber)
End Sub
End Module
10. LINQ (Language Integrated Query)
查询集合
- 使用 LINQ 查询集合数据。
Imports System.Linq
Module Module1
Sub Main()
Dim numbers() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim evenNumbers = From num In numbers
Where num Mod 2 = 0
Select num
Console.WriteLine("Even numbers:")
For Each num In evenNumbers
Console.WriteLine(num)
Next
End Sub
End Module
查询数据库
- 使用 LINQ to SQL 或 Entity Framework 查询数据库。
Imports System
Imports System.Linq
Imports Microsoft.EntityFrameworkCore
Module Module1
Sub Main()
Using context As New MyDbContext()
Dim customers = From c In context.Customers
Where c.Age > 30
Select c
Console.WriteLine("Customers over 30 years old:")
For Each customer In customers
Console.WriteLine($"{customer.Name} ({customer.Age})")
Next
End Using
End Sub
End Module
Public Class MyDbContext
Inherits DbContext
Public Property Customers As DbSet(Of Customer)
End Class
Public Class Customer
Public Property Id As Integer
Public Property Name As String
Public Property Age As Integer
End Class
总结
以上是一个全面的 Visual Basic 入门教程,涵盖了从基础语法到类和对象、文件操作、异常处理、标准库和 LINQ 的基本步骤。通过这些基础知识,你可以开始编写简单的 Visual Basic 程序,并进一步探索更复杂的功能和创意。