例如,假设我有一个简单的类,我创建了一个对象,表示...
Public Class StackOverflow
Public Property Questions As String
Public Property Answers As String
Public Property Accepted As Integer
Public Property Boohoo As Boolean
End Class
Dim Noobie As New StackOverflow With {
.Questions = "How do I ?",
.Answers = "Like This",
.Accepted = 1,
.Boohoo = True}
Run Code Online (Sandbox Code Playgroud)
假设我有1000个标签,每个标签都包含一个带有自己内容的StackOverflow.当我将鼠标悬停在标签上时,我想在弹出窗口中显示每个属性.为了能够做到这一点,从我在StackOverflow上的答案的搜索结果,似乎我必须使用反射.根据这里的其他开发人员的说法,使用反射很慢,我只应该使用它.
是否有更好的方法来迭代对象以获取所有信息,以便我可以显示它,具体取决于鼠标悬停的标签?
编辑:在我的帖子中添加更多细节.我正在创建一个自定义地图,我正在绘制点到该地图上.当我创建一个点时,我继承了该类,因此它可以包含更多信息.例如...
Public Class PinPoint
Public Property X as Double
Public Property Y as Double
Public Property ExtraInfo1 as String
Public Property ExtraInfo2 as String
End Class
Run Code Online (Sandbox Code Playgroud)
当我为我的地图创建一个新点时,我会做类似的事情:
Dim Pin As New PinPoint With {.X = Xcoord, .Y = Ycoord, .ExtraInfo1 = "Info1", .ExtraInfo2 = "Info2"}
Run Code Online (Sandbox Code Playgroud)
当我把鼠标移到那些点上时......
Public Sub PinMouseOver()
Dim rowx As Label
Dim coly As Label
'Create a new Row and Col for the title
TableLayoutPanel1.RowStyles.Add(New RowStyle(SizeType.AutoSize))
TableLayoutPanel1.ColumnStyles.Add(New ColumnStyle(SizeType.AutoSize))
TableLayoutPanel1.RowCount += 1
TableLayoutPanel1.ColumnCount += 1
rowx = New Label With {.Text = "Title: "} : coly = New Label With {.Text = Pin.Title}
TableLayoutPanel1.Controls.Add(rowx, 0, TableLayoutPanel1.RowCount - 1)
TableLayoutPanel1.Controls.Add(coly, 1, TableLayoutPanel1.ColumnCount - 1)
'And then do the same for all the other properties.
End Sub
Run Code Online (Sandbox Code Playgroud)
我有一些几乎可以做到的事情
<Runtime.CompilerServices.Extension>
Public Function AllPropertiesString(instance As Object) As String
Try
If instance Is Nothing Then Return ""
Return String.Join(Environment.NewLine,
instance.GetType().
GetProperties().
Select(Function(pi) $"{pi.Name}{vbTab}{pi.GetValue(instance)}"))
Catch
Return ""
End Try
End Function
Run Code Online (Sandbox Code Playgroud)
用法
Dim Noobie As New StackOverflow With {
.Questions = "How do I ?",
.Answers = "Like This",
.Accepted = 1,
.Boohoo = True}
Dim result = Noobie.AllPropertiesString()
Console.WriteLine(result)
Run Code Online (Sandbox Code Playgroud)
产量
问题我如何? 接受
这样的答案
1
Boohoo True
你可以按照自己喜欢的方式格式化返回的字符串
根据您的评论,您可以返回Dictionary(Of String, Object)并按照您的意愿操纵名称和值.
<Runtime.CompilerServices.Extension>
Public Function AllPropertiesDictionary(instance As Object) As Dictionary(Of String, Object)
Try
If instance Is Nothing Then Return Nothing
Return instance.GetType().GetProperties().ToDictionary(Function(pi) pi.Name, Function(pi) pi.GetValue(instance))
Catch
Return Nothing
End Try
End Function
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |