对于这个模糊的问题,我深表歉意,但不确定如何进行。
我需要的是一种类似于具有各种字段和属性的类对象,用于存储数据。
但是,由于并非所有字段/属性在编译时都是已知的,因此我还需要能够在运行时添加和使用新的字段/属性。
这些对象随后将被排列在列表中,并按这些字段/属性中的值排序并绑定到WPF控件。
现在,我仅使用该类:具有各种属性的类对象,但是我开始遇到问题,需要在其中添加更多字段/属性。
在vb.net中我可以使用某些东西来实现此目的吗?
编辑:
好的,我会尝试说明。
目前我有这样的事情。
假设我已经定义了这样的对象
Public Class DataEntry
Public Property Name As String
Public Property Type As String
Public Property Msc As Integer
End Class
Run Code Online (Sandbox Code Playgroud)
如果我知道一开始将拥有的所有属性,那将很好地工作。如果突然需要添加其他属性,则会遇到问题:
Public Class DataEntry
Public Property Name As String
Public Property Type As String
Public Property Msc As Integer
Public Property AdditionalDescription As String
End Class
Run Code Online (Sandbox Code Playgroud)
当然,我可以重新编译整个内容,但是由于我不知道最终需要的所有可能的属性,我想知道,也许有一种方法可以从运行时实现?
还是应该使用复杂的数组堆而不是自定义对象?
在运行时无法向类添加新属性。
如果您不想提前将可能不使用的属性添加到类中,则可以使用字典来存储直到运行时才知道的“属性”。
Public Property RunTimeProperties As New Dictionary(Of String, Object)
Run Code Online (Sandbox Code Playgroud)
拥有“对象”类型值的字典几乎可以存储任何内容。字符串,数组,列表等
RunTimeProperties.Add("Length", 100)
RunTimeProperties.Add("Height", 200)
RunTimeProperties.Add("MiddleName", "Rupert")
RunTimeProperties.Add("SiblingsNames", New String() {"John", "Sarah", "Michael"})
Run Code Online (Sandbox Code Playgroud)
您可以使用TryGetValue方法从字典中获取值。
Dim value As Object
If RunTimeProperties.TryGetValue("Length", value) Then
' Length was found in the dictionary
Else
' Length was not found in the dictionary
End If
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3322 次 |
| 最近记录: |