可以使用反射来遍历类中的属性并赋值。下面是一个示例代码:
Imports System.Reflection
Public Class MyClass
Public Property Name As String
Public Property Age As Integer
Public Property Gender As String
End Class
Public Sub Main()
Dim myObject As New MyClass()
' 获取 MyClass 类的所有属性
Dim properties As PropertyInfo() = GetType(MyClass).GetProperties()
' 遍历属性并赋值
For Each prop As PropertyInfo In properties
' 判断属性是否可写
If prop.CanWrite Then
' 根据属性类型设置不同的值
Select Case prop.PropertyType
Case GetType(String)
prop.SetValue(myObject, "John")
Case GetType(Integer)
prop.SetValue(myObject, 25)
Case GetType(Boolean)
prop.SetValue(myObject, True)
' 可根据需要添加其他属性类型的赋值逻辑
Case Else
' 默认赋值为 Nothing
prop.SetValue(myObject, Nothing)
End Select
End If
Next
' 输出属性值
Console.WriteLine("Name: " & myObject.Name)
Console.WriteLine("Age: " & myObject.Age)
Console.WriteLine("Gender: " & myObject.Gender)
End Sub
这个示例代码会遍历 MyClass
类的所有属性,并根据属性的类型赋予不同的值。最后输出属性的值。
下一篇:遍历链表