【问题标题】:access class property using a variable name that user input使用用户输入的变量名访问类属性
【发布时间】:2020-05-31 03:59:48
【问题描述】:

所以基本上我有一个类似于以下但更长的课程

Public Class inventory
    Public Property id As Integer
    Public Property name As String
End Class

在其他类中,我有一个称为类库存顺序的列表 所以当我遍历列表时,我可以这样做

For Each i In orders
        Console.WriteLine(i.name)
Next

但我想要一个变量在现场。 很喜欢

Dim rrr As String = Console.ReadLine()
For Each i In orders
     Console.WriteLine(i.rrr)
Next

但是我收到错误,因为 rrr 不是库存中的成员! 所以请任何人知道如何解决这个问题并能够从变量中访问该类让我知道 谢谢

【问题讨论】:

  • 也许类不是保存数据的最佳方式,考虑使用Dictionary<string, SomeTypeHere>
  • 你想用那个变量做什么?不清楚您想要发现一个变量是什么意思?
  • 对不起,我在运行时会动态更改变量名。
  • 你的意思是dim theOrderISeek = orders.FirstOrDefault(function(o) o.Name.Equals(rrr))? (或Contains(rrr)StartsWith(rrr) 或...)
  • rrr 是一个变量名,它的值指向类属性。所以在上面的例子中,rrr 的值将是 name 或 id

标签: c# asp.net .net vb.net visual-studio


【解决方案1】:

Get property value from string using reflection in C# 提供了答案,但它是 C#。以下是vb.net翻译。

Public Class inventory
    Public Property id As Integer
    Public Property name As String
    'I added a custom constructor to make filling a list easier for me
    Public Sub New(i As Integer, n As String)
        id = i
        name = n
    End Sub
    'add back default constructor
    Public Sub New()

    End Sub
End Class

Private orders As New List(Of inventory) From {New inventory(1, "Apples"), New inventory(2, "Oranges"), New inventory(3, "Pears")}

Private Sub OPCode()
    Dim rrr As String = "name" 'Console.ReadLine() as if user typed in name
    For Each i In orders
        Console.WriteLine(GetPropertyValue(i, rrr))
    Next
End Sub

Private Function GetPropertyValue(src As Object, PropName As String) As Object
    Return src.GetType().GetProperty(PropName).GetValue(src, Nothing)
End Function

输出:

苹果

橙子

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2021-02-15
    • 2017-11-01
    相关资源
    最近更新 更多