首页 > 解决方案 > 遍历对象中的属性并填充它

问题描述

我正在尝试遍历对象中的属性并将其应用为字符串。

例如,动态执行将是:

Dim objAnswers As New DAL.Quiz.QuizAnswers
    With objAnswers
        .Question1 = "text1"
        .Question2 = "text2"
        .Question3 = "text3"
        .Question4 = "text4"
        .Question5 = "text5"
    End With

但我试图遍历对象的属性,然后像这样应用它:

Dim objAnswers As New DAL.Quiz.QuizAnswers
    For Each rptItem As RepeaterItem In repeater1.Items
        Dim ddlAnswers As App_Controls_Forms_DropDownList = CType(rptItem.FindControl("DropDownList1"), App_Controls_Forms_DropDownList)
        For Each p As System.Reflection.PropertyInfo In objAnswers.GetType().GetProperties()
            If p.ToString.StartsWith("question") Then
                p = ddlAnswers.SelectedText
            End If
        Next
    Next

我试图用转发器中下拉列表中的 s 填充对象的字符串。这是我试图以伪方式执行的操作 - 对于中继器中的每一行,从下拉列表中获取文本并填充以“问题”开头的对象属性

谢谢您的帮助!

编辑:

Dim objAnswers As New DAL.Quiz.QuizAnswers
    For Each p As System.Reflection.PropertyInfo In objAnswers.GetType().GetProperties()
        For Each rptItem As RepeaterItem In repeater1.Items
            Dim ddlAnswers As App_Controls_Forms_DropDownList = CType(rptItem.FindControl("DropDownList1"), App_Controls_Forms_DropDownList)
            If p.ToString.StartsWith("Question") Then
                p.SetValue(objAnswers, ddlAnswers.SelectedText)
            End If
        Next
    Next

标签: asp.net.netvb.net

解决方案


我不使用 vb,所以有些名称可能是错误的。我会循环这些项目,找到单个匹配属性并将其设置如下:

Dim objAnswers As New DAL.Quiz.QuizAnswers
Dim i as Integer
For i = 0 To repeater1.Items.Length - 1
    Dim ddlAnswers As App_Controls_Forms_DropDownList = CType(repeater1.Items[i].FindControl("DropDownList1"), App_Controls_Forms_DropDownList)
    Dim p as System.Reflection.PropertyInfo = objAnswers.GetType().GetProperty("Question" & i + 1)
    p.SetValue(objAnswers, ddlAnswers.SelectedText)
Next

推荐阅读