簡體   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