簡體   English   中英

通過包含屬性名稱的字符串引用 class 的屬性

[英]Reference to an attribute of a class by means of a string containing the name of the property

讓我們舉一個非常簡短的 class 示例,如下所示:

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 執行相同的操作,所以我想創建一個 function 來執行這樣的操作,並以某種方式指示 VB 在每次調用時使用給定的屬性。

你能想出一種優雅的方式來做到這一點嗎?

編輯例如,假設我要執行的操作是字典中每個 Property1_Integer 或 Property2_Single 成員的總和。 我真正真正想做的是確定所有值是否相同,或者是否至少有一個不同。

您可以使用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

玩得開心!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM