通过包含属性名称的字符串引用类的属性

时间:2020-06-11 22:34:11

标签: vb.net

让我们举一个简短的例子,像这样的类:

Public Class The_Class1
    Public Property ID As Integer
    Public Property Property1_Integer As Integer
    Public Property Property2_Single As Single
End Class

在其他地方,我有一本包含The_Class1实例的字典,如下所示:

Public Dictionary_Class1 As New Dictionary(Of Integer, The_Class1)

我想对Dictionary_Class1内部的所有成员执行Property1_Integer上的操作。另外,我想对Property2_Single执行相同的操作,因此我想创建一个函数来执行此操作,并以某种方式指示VB在每次调用时使用给定的属性。

您能想到一种优雅的方法吗?

编辑:例如,以 为例,我要执行的操作是字典中成员的每个Property1_Integer或Property2_Single之和。我真正想做的是确定所有值是否相同,或者是否至少有一个不同的值。

1 个答案:

答案 0 :(得分:1)

您可以使用Reflection,但是它并不像您想象的那么干净。这是一些您可以适应需要的基本代码:

Public Class The_Class1
    Public Property ID As Integer
    Public Property Property1_Integer As Integer
    Public Property Property2_Single As Single
End Class

Private Sub SetProperty1_Integer()
    Dim myClassInstance As New The_Class1
    Dim myType As Type = GetType(The_Class1)
    Dim propertyInfo As System.Reflection.PropertyInfo = myType.GetProperty("Property1_Integer")

    propertyInfo.SetValue(myClassInstance, 1)
    MessageBox.Show(myClassInstance.Property1_Integer.ToString)
End Sub

玩得开心!

相关问题