以下是50个常用的Visual Basic代码示例:
1. 声明变量
```vb
Dim name As String
Dim age As Integer
Dim height As Double
```
2. 常量
```vb
Const pi As Double = 3.14159
```
3. 数组
```vb
Dim numbers(5) As Integer
Dim names(3) As String
```
4. 控制台输入/输出
```vb
Console.WriteLine("Hello, World!")
Dim input As String = Console.ReadLine()
```
5. 循环
```vb
For i As Integer = 0 To 9
Console.WriteLine(i)
Next
Do While i < 10
Console.WriteLine(i)
i += 1
Loop
While i < 10
Console.WriteLine(i)
i += 1
End While
```
6. 条件语句
```vb
If age >= 18 Then
Console.WriteLine("You are an adult.")
Else
Console.WriteLine("You are not an adult.")
End If
Select Case age
Case 0 To 12
Console.WriteLine("You are a child.")
Case 13 To 19
Console.WriteLine("You are a teenager.")
Case Else
Console.WriteLine("You are an adult.")
End Select
```
7. 函数/子程序
```vb
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
Sub PrintHello()
Console.WriteLine("Hello, World!")
End Sub
```
8. 类
```vb
Public 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 Function Introduce() As String
Return #34;My name is {Name} and I am {Age} years old."
End Function
End Class
```
9. 文件操作
```vb
Dim filePath As String = "C:\example.txt"
' 读取文件
Dim lines As String() = File.ReadAllLines(filePath)
' 写入文件
File.WriteAllText(filePath, "Hello, World!")
' 追加文件
File.AppendAllText(filePath, "This is a new line.")
```
10. 异常处理
```vb
Try
' 可能引发异常的代码
Catch ex As Exception
Console.WriteLine(#34;An error occurred: {ex.Message}")
End Try
```
11. 字符串操作
```vb
Dim text As String = "Hello, World!"
Dim length As Integer = text.Length
Dim upperText As String = text.ToUpper()
Dim lowerText As String = text.ToLower()
Dim index As Integer = text.IndexOf("World")
Dim substring As String = text.Substring(0, 5)
Dim splitText() As String = text.Split(","c)
```
12. 日期和时间
```vb
Dim now As DateTime = DateTime.Now
Dim today As DateTime = DateTime.Today
Dim tomorrow As DateTime = now.AddDays(1)
Dim formattedDate As String = now.ToString("yyyy-MM-dd")
```
13. 随机数
```vb
Dim random As New Random()
Dim randomNumber As Integer = random.Next(1, 101)
```
14. 正则表达式
```vb
Dim pattern As String = "\d+"
Dim input As String = "Number 123 and number 456."
Dim regex As New Regex(pattern)
Dim matches As MatchCollection = regex.Matches(input)
```
15. 集合
```vb
Dim list As New List(Of String) From {"apple", "banana", "cherry"}
Dim dictionary As New Dictionary(Of String, Integer) From {{"apple", 1}, {"banana", 2}, {"cherry", 3}}
```
16. 数学操作
```vb
Dim a As Double = 5
Dim b As Double = 2
Dim sum As Double = a + b
Dim difference As Double = a - b
Dim product As Double = a * b
Dim quotient As Double = a / b
Dim remainder As Double = a Mod b
```
17. 类型转换
```vb
Dim number As Integer = 123
Dim text As String = number.ToString()
Dim textNumber As String = "123"
Dim numberFromText As Integer = Integer.Parse(textNumber)
```
18. 错误处理
```vb
On Error Resume Next
' 可能引发错误的代码
If Err.Number <> 0 Then
Console.WriteLine(#34;An error occurred: {Err.Description}")
Err.Clear()
End If
```
19. 文件操作(读取文件)
```vb
Dim filePath As String = "C:\example.txt"
Dim fileContents As String = My.Computer.FileSystem.ReadAllText(filePath)
```
20. 文件操作(写入文件)
```vb
Dim filePath As String = "C:\example.txt"
Dim text As String = "Hello, World!"
My.Computer.FileSystem.WriteAllText(filePath, text, False)
```
21. 文件操作(追加文件)
```vb
Dim filePath As String = "C:\example.txt"
Dim text As String = "This is a new line."
My.Computer.FileSystem.WriteAllText(filePath, text, True)
```
22. 文件操作(复制文件)
```vb
Dim sourcePath As String = "C:\source.txt"
Dim destinationPath As String = "C:\destination.txt"
My.Computer.FileSystem.CopyFile(sourcePath, destinationPath, True)
```
23. 文件操作(移动文件)
```vb
Dim sourcePath As String = "C:\source.txt"
Dim destinationPath As String = "C:\destination.txt"
My.Computer.FileSystem.MoveFile(sourcePath, destinationPath)
```
24. 文件操作(删除文件)
```vb
Dim filePath As String = "C:\example.txt"
My.Computer.FileSystem.DeleteFile(filePath)
```
25. 文件操作(获取文件信息)
```vb
Dim filePath As String = "C:\example.txt"
Dim fileInfo As FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
Dim fileName As String = fileInfo.Name
Dim fileSize As Long = fileInfo.Length
```
26. 文件操作(获取目录信息)
```vb
Dim directoryPath As String = "C:\example"
Dim directoryInfo As DirectoryInfo = My.Computer.FileSystem.GetDirectoryInfo(directoryPath)
Dim directoryName As String = directoryInfo.Name
```
27. 文件操作(创建目录)
```vb
Dim directoryPath As String = "C:\example"
My.Computer.FileSystem.CreateDirectory(directoryPath)
```
28. 文件操作(复制目录)
```vb
Dim sourcePath As String = "C:\source"
Dim destinationPath As String = "C:\destination"
My.Computer.FileSystem.CopyDirectory(sourcePath, destinationPath, True)
```
29. 文件操作(移动目录)
```vb
Dim sourcePath As String = "C:\source"
Dim destinationPath As String = "C:\destination"
My.Computer.FileSystem.MoveDirectory(sourcePath, destinationPath)
```
30. 文件操作(删除目录)
```vb
Dim directoryPath As String = "C:\example"
My.Computer.FileSystem.DeleteDirectory(directoryPath, FileIO.DeleteDirectoryOption.DeleteAllContents)
```
31. 文件操作(获取目录中的文件)
```vb
Dim directoryPath As String = "C:\example"
Dim files() As FileInfo = My.Computer.FileSystem.GetFiles(directoryPath)
```
32. 文件操作(获取目录中的子目录)
```vb
Dim directoryPath As String = "C:\example"
Dim directories() As DirectoryInfo = My.Computer.FileSystem.GetDirectories(directoryPath)
```
33. 文件操作(检查文件是否存在)
```vb
Dim filePath As String = "C:\example.txt"
Dim fileExists As Boolean = My.Computer.FileSystem.FileExists(filePath)
```
34. 文件操作(检查目录是否存在)
```vb
Dim directoryPath As String = "C:\example"
Dim directoryExists As Boolean = My.Computer.FileSystem.DirectoryExists(directoryPath)
```
35. 文件操作(读取二进制文件)
```vb
Dim filePath As String = "C:\example.bin"
Dim bytes() As Byte = My.Computer.FileSystem.ReadAllBytes(filePath)
```
36. 文件操作(写入二进制文件)
```vb
Dim filePath As String = "C:\example.bin"
Dim bytes() As Byte = {&H01, &H02, &H03}
My.Computer.FileSystem.WriteAllBytes(filePath, bytes, False)
```
37. 文件操作(追加二进制文件)
```vb
Dim filePath As String = "C:\example.bin"
Dim bytes() As Byte = {&H04, &H05, &H06}
My.Computer.FileSystem.WriteAllBytes(filePath, bytes, True)
```
38. 网络操作(下载文件)
```vb
Dim url As String = "https://example.com/file.txt"
Dim filePath As String = "C:\file.txt"
My.Computer.Network.DownloadFile(url, filePath)
```
39. 网络操作(上传文件)
```vb
Dim url As String = "https://example.com/upload"
Dim filePath As String = "C:\file.txt"
My.Computer.Network.UploadFile(filePath, url)
```
40. 网络操作(发送HTTP请求)
```vb
Dim url As String = "https://example.com/api"
Dim data As String = "key=value"
Dim response As String = My.Computer.Network.UploadData(url, System.Text.Encoding.ASCII.GetBytes(data))
```
41. 网络操作(获取网页内容)
```vb
Dim url As String = "https://example.com"
Dim content As String = My.Computer.Network.DownloadString(url)
```
42. 网络操作(检查网络连接)
```vb
Dim connected As Boolean = My.Computer.Network.IsAvailable
```
43. 网络操作(Ping)
```vb
Dim host As String = "example.com"
Dim pingTime As Long = My.Computer.Network.Ping(host)
```
44. 系统操作(获取系统信息)
```vb
Dim osVersion As String = My.Computer.Info.OSVersion
Dim osPlatform As String = My.Computer.Info.OSPlatform
Dim osFullName As String = My.Computer.Info.OSFullName
```
45. 系统操作(获取硬件信息)
```vb
Dim totalMemory As Long = My.Computer.Info.TotalPhysicalMemory
Dim availableMemory As Long = My.Computer.Info.AvailablePhysicalMemory
Dim totalVirtualMemory As Long = My.Computer.Info.TotalVirtualMemory
Dim availableVirtualMemory As Long = My.Computer.Info.AvailableVirtualMemory
```
46. 系统操作(获取CPU信息)
```vb
Dim cpuName As String = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0", "ProcessorNameString", Nothing)
```
47. 系统操作(获取显卡信息)
```vb
Dim videoCard As String = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\VideoBios", "VideoBiosString", Nothing)
```
48. 系统操作(获取磁盘信息)
```vb
Dim drives() As DriveInfo = DriveInfo.GetDrives()
For Each drive As DriveInfo In drives
Dim driveName As String = drive.Name
Dim driveType As String = drive.DriveType.ToString()
Dim totalSize As Long = drive.TotalSize
Dim availableSize As Long = drive.AvailableFreeSpace
Next
```
49. 系统操作(获取内存信息)
```vb
Dim memoryInfo As New ManagementObject("win32_physicalmemory.deviceid=""Physical Memory 0""")
Dim capacity As Long = memoryInfo("Capacity")
```
50. 系统操作(获取屏幕分辨率)
```vb
Dim screenWidth As Integer = My.Computer.Screen.Bounds.Width
Dim screenHeight As Integer = My.Computer.Screen.Bounds.Height
```