asp.net - 遍历对象中的属性并填充它
问题描述
我正在尝试遍历对象中的属性并将其应用为字符串。
例如,动态执行将是:
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
解决方案
我不使用 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
推荐阅读
- php - 如何在 wordpress 中添加可编辑的超链接?
- android - 未找到 ID 为“kotlin-android”的插件。尝试运行我的代码时给我这个错误
- ajax - 使用 Ajax 应用编辑/删除数据表时的问题
- mysql - 如何构建具有多种类型项目(服务、零件和保险等)的模式
- docker - docker如何清理deployment生成的过期镜像和容器
- python - 切片熊猫数据框列表
- python - 使用 YOLOv3 进行目标检测
- reactjs - 错误:拒绝在“tus-js-client”npm 包中获取不安全的标头“Location”
- tiff - 如何确定 tiff 是否以 bigtiff 格式编写
- gatsby - 在没有 GraphQL 的情况下使用 gatsby-image?