繁体   English   中英

如果我遍历对象以获取所有属性,性能将如何?

[英]How is performance going to be if I iterate through an object to get all the properties?

例如,假设我有一个简单的类,并为此创建了一个对象...

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}

假设我有1000个标签,每个标签包含一个StackOverflow及其自己的内容。 当我将鼠标悬停在标签上时,我想在弹出窗口中显示每个属性。 为了做到这一点,从我对StackOverflow答案的搜索结果来看,我似乎必须使用Reflection。 并且根据此处的其他开发人员,使用反射很慢,我仅在必要时才使用它。

是否有更好的方法遍历对象以获取所有信息,以便我可以根据鼠标悬停的标签进行显示?

编辑:添加一些更多的细节到我的帖子。 我正在创建自定义地图,并在该地图上绘制点。 创建点时,我继承了该类,因此它可以包含更多信息。 例如...

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

当我为地图创建新点时,我将执行以下操作:

Dim Pin As New PinPoint With {.X = Xcoord, .Y = Ycoord, .ExtraInfo1 = "Info1", .ExtraInfo2 = "Info2"}

当我将鼠标悬停在这些点上时...

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

我几乎可以做到这一点

<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

用法

Dim Noobie As New StackOverflow With {
    .Questions = "How do I  ?",
    .Answers = "Like This",
    .Accepted = 1,
    .Boohoo = True}

Dim result = Noobie.AllPropertiesString()

Console.WriteLine(result)

输出

问题我该怎么办?
像这样的答案
已接受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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM