You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.Net如何实现Sub过程接收不同类型对象传入?

让Sub同时支持DoorDescription和WindowDescription类型参数的解决方案

针对需求,我们可以利用面向对象的多态性,通过定义公共接口或基类来统一处理这两个具有相同属性的类,以下是两种可行方案:

方案1:定义公共接口(推荐)

因为DoorDescription和WindowDescription都包含MirrorFeatures属性,先定义一个包含该属性的接口,让两个类实现这个接口:

步骤1:定义接口

Public Interface IHasMirrorFeatures
    Property MirrorFeatures As List(Of Feature)
End Interface

步骤2:修改类实现接口

Public Class DoorDescription
    Implements IHasMirrorFeatures
    ' 实现接口的属性
    Public Property MirrorFeatures As New List(Of Feature) Implements IHasMirrorFeatures.MirrorFeatures
End Class

Public Class WindowDescription
    Implements IHasMirrorFeatures
    ' 实现接口的属性
    Public Property MirrorFeatures As New List(Of Feature) Implements IHasMirrorFeatures.MirrorFeatures
End Class

步骤3:改造exampleSub

将参数类型改为接口类型,同时增加空值判断避免空引用异常:

Protected Shared Sub exampleSub(Optional ByRef partDescription As IHasMirrorFeatures = Nothing)
    If partDescription IsNot Nothing Then
        For Each feat In partDescription.MirrorFeatures
            ' 保留原有的循环逻辑
        Next
    End If
End Sub

调用方式

无需修改调用代码,直接传入两种类型的对象即可:

exampleSub(New DoorDescription())
exampleSub(New WindowDescription())

方案2:定义公共基类

如果后续可能扩展更多类似的类,且它们有更多共性,可以用基类的方式:

步骤1:定义基类

Public MustInherit Class BaseDescription
    Public Property MirrorFeatures As New List(Of Feature)
End Class

步骤2:修改类继承基类

Public Class DoorDescription
    Inherits BaseDescription
End Class

Public Class WindowDescription
    Inherits BaseDescription
End Class

步骤3:改造exampleSub

将参数类型改为基类类型,同样增加空值判断:

Protected Shared Sub exampleSub(Optional ByRef partDescription As BaseDescription = Nothing)
    If partDescription IsNot Nothing Then
        For Each feat In partDescription.MirrorFeatures
            ' 保留原有的循环逻辑
        Next
    End If
End Sub

额外建议

原代码中使用了ByRef参数,如果你的Sub不需要重新赋值传入的对象本身(只是访问其属性),建议改为ByVal,这样更符合常规用法且更安全:

Protected Shared Sub exampleSub(Optional ByVal partDescription As IHasMirrorFeatures = Nothing)
    ' 逻辑不变
End Sub

内容的提问来源于stack exchange,提问作者yAaFN5if7DiVDMn9UjmkXDFJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 23:07:27