我对反射不是很精通,但是几天来我一直在研究这段代码,试图获取类属性的值。我正在使用 API 来查找由 VisualCron 程序管理的 cron 作业中的值。
我会稍微解释一下结构。每个 cron 作业内部都有几个任务,它们有自己的设置。这些设置存储在 TaskClass 类中的属性中,声明如下:
Public Property <propertyname> As <classname>
每个属性都与自己的类相关联,因此例如在 TaskClass 中有一个 Execute 属性,声明如下:
Public Property Execute As TaskExecuteClass
TaskExecuteClass 内部是保存我需要的值的属性。使用下面的代码块,我已经能够检索除字符串之外的所有类型的属性值。巧合的是,字符串值是我需要获取的唯一值。
我知道我所写的内容一定有问题导致了这种情况,因为经过大量搜索后我找不到任何有类似问题的人。任何人都可以帮助我吗?
Dim strAdd As String = ""
For Each t As VisualCronAPI.Server In vcClient.Servers.GetAll()
For Each f As VisualCron.JobClass In t.Jobs.GetAll
For Each s As VisualCron.TaskClass In f.Tasks
Dim propVal As Object
Dim propInfo As PropertyInfo() = s.GetType().GetProperties()
For i As Integer = 0 To propInfo.Length - 1
With propInfo(i)
If s.TaskType.ToString = propInfo(i).Name.ToString Then
Dim asm As Assembly = Assembly.Load("VisualCron")
Dim typeName As String = String.Format("VisualCron.{0}", propInfo(i).PropertyType.Name)
Dim tp As Type = asm.GetType(typeName)
Dim construct As ConstructorInfo = tp.GetConstructor(Type.EmptyTypes)
Dim classInst As Object = construct.Invoke(Nothing)
Dim classProps As PropertyInfo() = classInst.GetType().GetProperties()
For h As Integer = 0 To classProps.Length - 1
With classProps(h)
If .GetIndexParameters().Length = 0 Then
propVal = .GetValue(classInst, Nothing)
If Not propVal Is Nothing Then
strAdd = f.Name & " - " & s.Name & " - " & .Name & " - " & propVal.ToString
End If
End If
If strAdd <> "" Then
ListBox1.Items.Add(strAdd)
End If
End With
Next
End If
End With
Next
Next s
Next f
Next t