VB.Net中的引用传递
我以前发布过一个类似的问题,它在C#中有效(感谢社区),但实际问题是在VB.Net中(选项严格打开)。问题是考试并没有通过VB.Net中的引用传递,vb.net,Vb.net,我以前发布过一个类似的问题,它在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 Pro
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
公共接口的可扩展性
属性Id()为整数
端接口
公营货柜
实现灵活性
Private\u名称作为字符串
私有_id为整数
公共属性Id()作为整数实现了IEntity.Id
得到
返回id
结束
设置(ByVal值为整数)
_id=值
端集
端属性
作为字符串的公共属性名()
得到
返回\u名称
结束
设置(ByVal值作为字符串)
_名称=值
端集
端属性
末级
公共类命令
公共子应用程序社区(ByRef实体作为用户)
将innerEntity作为具有{.Name=“CommandContainer”,.Id=20}的新容器
实体=内部实体
端接头
末级
_
公共类DirectCastTest
_
公共子系统在DirectCast()上丢失值
Dim实体作为新容器,带有{.Name=“Container”,.Id=0}
Dim cmd作为新命令
cmd.ApplyCommand(DirectCast(实体、实体))
Assert.AreEqual(entity.Id,20)
Assert.AreEqual(entity.Name,“CommandContainer”)
端接头
末级
VB中的情况与C#中的情况相同。通过使用DirectCast
,可以有效地创建一个临时局部变量,然后通过引用传递该变量。这是一个与实体
局部变量完全分离的局部变量
这应该起作用:
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
当然,让函数返回新实体作为其返回值会更简单…VB中的情况与C#中的情况相同。通过使用
DirectCast
,可以有效地创建一个临时局部变量,然后通过引用传递该变量。这是一个与实体
局部变量完全分离的局部变量
这应该起作用:
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
当然,让函数返回新实体作为其返回值会更简单…对不起,问题是测试没有通过