我应该使用String和Integer两种方法,还是使用TypeOf?

时间:2015-07-15 21:27:13

标签: vb.net polymorphism

我们有一系列对象集合,它们都有两个肯定的字段,一个整数“key”和一个字符串“name”。我们有基于名称或密钥返回特定实例的方法......

Public ReadOnly Property Inflations(ByVal K as String) As InflationRow
    ' look for K in the names
End Property
Public ReadOnly Property Inflations(ByVal K as Integer) As InflationRow
    ' look for K in the keys
End Property

COM互操作具有有趣的副作用,即只导出具有给定名称的第一个方法。所以我们添加了这个......

Public ReadOnly Property Inflations(ByVal K as Object) As InflationRow
    Return Inflations(K)
End Property

这在阅读代码时会导致一些混乱,而多行会做同样的事情。那么如果我用...替换所有这些呢?

Public ReadOnly Property Inflations(ByVal K as Object) As InflationRow
    If TypeOf K Is String then
        'do a string lookup on name
    else
        'try it on the key
    end if
End Property

这最终会做同样的事情,但似乎更容易阅读并将所有代码保存在同一个地方。但...

对此代码的大多数调用不是来自COM,而是来自我们自己的代码。我们的.net代码中对TypeOf的许多调用会比允许运行时通过多态来做出这个决定要慢得多吗?我真的不太了解运行时甚至猜测。

1 个答案:

答案 0 :(得分:2)

测试一下,看看! : - )

Option Strict On

Module Module1
  Sub Main()
    Dim irc As New InflationRowCollection
    For i As Integer = 0 To 4999
      irc.InflationList.Add(New InflationRow With {.IntProperty = i, .StrProperty = i.ToString})
    Next i
    Dim t1 As Date = Now
    For i As Integer = 0 To 4999
      Dim ir1 As InflationRow = irc.Inflations(i)
      Dim ir2 As InflationRow = irc.Inflations(i.ToString)
    Next i
    Dim t2 As Date = Now
    For i As Integer = 0 To 4999
      Dim ir1 As InflationRow = irc.InflationsObj(i)
      Dim ir2 As InflationRow = irc.InflationsObj(i.ToString)
    Next i
    Dim t3 As Date = Now
    Console.WriteLine("Typed property: " & (t2 - t1).TotalSeconds & " sec" & vbCrLf & "Object property: " & (t3 - t2).TotalSeconds & " sec")
    Console.ReadKey()
  End Sub
End Module

Class InflationRow
  Property IntProperty As Integer
  Property StrProperty As String
End Class

Class InflationRowCollection
  Property InflationList As New List(Of InflationRow)

  ReadOnly Property InflationsObj(o As Object) As InflationRow 'use different name for testing, so we can compare
    Get
      If TypeOf o Is String Then
        Return Inflations(DirectCast(o, String))
      ElseIf TypeOf o Is Integer Then
        Return Inflations(DirectCast(o, Integer))
      Else
        Throw New ArgumentException
      End If
    End Get
  End Property

  ReadOnly Property Inflations(k As String) As InflationRow
    Get
      For Each ir As InflationRow In InflationList
        If ir.StrProperty = k Then Return ir
      Next
      Return Nothing
    End Get
  End Property

  ReadOnly Property Inflations(k As Integer) As InflationRow
    Get
      For Each ir As InflationRow In InflationList
        If ir.IntProperty = k Then Return ir
      Next
      Return Nothing
    End Get
  End Property
End Class