2009-11-20 54 views
0

我之前發佈了一個類似的問題,它在C#中工作(感謝社區),但實際問題出現在VB.Net中(選項嚴格)。問題是測試沒有通過。在VB.Net中通過引用傳遞

Public Interface IEntity 
    Property Id() As Integer 
End Interface 

    Public Class Container 
    Implements IEntity 
    Private _name As String 
    Private _id As Integer 
    Public Property Id() As Integer Implements IEntity.Id 
     Get 
      Return _id 
     End Get 
     Set(ByVal value As Integer) 
      _id = value 
     End Set 
    End Property 

    Public Property Name() As String 
     Get 
      Return _name 
     End Get 
     Set(ByVal value As String) 
      _name = value 
     End Set 
    End Property 
End Class 

Public Class Command 
    Public Sub ApplyCommand(ByRef entity As IEntity) 
     Dim innerEntity As New Container With {.Name = "CommandContainer", .Id = 20} 
     entity = innerEntity 
    End Sub 
End Class 

<TestFixture()> _ 
Public Class DirectCastTest 
    <Test()> _ 
    Public Sub Loosing_Value_On_DirectCast() 
     Dim entity As New Container With {.Name = "Container", .Id = 0} 
     Dim cmd As New Command 
     cmd.ApplyCommand(DirectCast(entity, IEntity)) 
     Assert.AreEqual(entity.Id, 20) 
     Assert.AreEqual(entity.Name, "CommandContainer") 
    End Sub 
End Class 
+0

有什麼問題嗎? – JonH

+0

對不起,問題是測試沒有通過 –

回答

4

在VB中和在C#中一樣。通過使用DirectCast,您可以有效地創建一個臨時局部變量,然後通過引用傳遞。這是一個與entity局部變量完全分離的局部變量。

這應該工作:

Public Sub Losing_Value_On_DirectCast() 
    Dim entity As New Container With {.Name = "Container", .Id = 0} 
    Dim cmd As New Command 
    Dim tmp As IEntity = entity 
    cmd.ApplyCommand(tmp) 
    entity = DirectCast(tmp, Container) 
    Assert.AreEqual(entity.Id, 20) 
    Assert.AreEqual(entity.Name, "CommandContainer") 
End Sub 

當然會比較簡單只是爲了讓函數返回新實體作爲其返回值...

+0

哇,今天我學到了一些新東西... – Walter