我之前发过一个类似的问题,它在C#中工作(感谢社区),但实际问题出在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 :(得分: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
当然,只是让函数返回新实体作为其返回值...
会更简单