2009-11-20 55 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