【问题标题】:Get values from List without know the names of variables在不知道变量名称的情况下从 List 获取值
【发布时间】:2019-10-11 10:31:20
【问题描述】:

我遇到了一些问题,我想知道如何解决这些问题。 是否可以在不知道变量名称的情况下从匿名类型的对象中获取值?

我有 2 个组合框:

With combobox1
  .ItemsSource = list1
  .DisplayMemberPath = "Name"
  .SelectedValuePath = "Age"
End With

With combobox2
  .ItemsSource = list2
  .DisplayMemberPath = "Address"
  .SelectedValuePath = "Number"
End With

我想从选定的组合框中获取值,但我想要一个普通的子:

Dim list As New List(Of Object)

Private Sub FilterCombobox(combobox as Combobox)
  For Each item In combobox.Items
    list.Add(New With {.Value = item.????,
                       .Display = item.????})
  Next
End Sub

如何在 For Each 上调用 DisplayMemberPath 和 SelectedValuePath?

.Value = item.SelectedValuePath 
.Display = item.DisplayMemberPath

我想访问这些值,但如您所见,项目名称不同。 我需要动态访问这些数据。

【问题讨论】:

    标签: .net wpf vb.net


    【解决方案1】:

    您可以使用反射来做到这一点:

    Private Sub FilterCombobox(combobox As ComboBox)
    
        If combobox IsNot Nothing And combobox.Items.Count > 0 Then
            Dim type = combobox.Items(0).GetType()
            Dim displayMemberPath = type.GetProperty(combobox.DisplayMemberPath)
            Dim selectedValuePath = type.GetProperty(combobox.SelectedValuePath)
    
            For Each item In combobox.Items
                List.Add(New With {.Value = selectedValuePath.GetValue(item),
                           .Display = displayMemberPath.GetValue(item)})
            Next
        End If
    End Sub
    

    【讨论】:

    • 不错!这就是我一直在寻找的。​​span>
    猜你喜欢
    • 2016-11-10
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    相关资源
    最近更新 更多