【问题标题】:VB.Net: Byref-in a parent type but return child type to ByRefVB.Net:Byref-在父类型中但将子类型返回给 ByRef
【发布时间】:2014-10-08 23:45:58
【问题描述】:

在这种情况下如何保持子类型返回到 ByRef 引用的变量?

Public Class Father
End Class

Public Class Son
   Inherits Father
End Class

' Should return a Son, not a Father
Public Sub Save(ByRef obj as Father)

【问题讨论】:

  • 这应该是一个函数。谷歌“工厂方法模式”以了解更多信息。
  • 儿子不一定是父亲,我希望我的儿子暂时不会……你能把它改成函数吗?公共函数 Save(ByVal obj as Father) As Son

标签: .net vb.net class inheritance byref


【解决方案1】:

但您可以指定Son,如果您愿意:

' Should return a Son, not a Father
Public Sub Save(ByRef obj As Father)
    obj = New Son
End Sub

现在,当您调用 Save 时,您有一个 Son 而不是 Father:

Dim father As New Father
Save(father)
If TypeOf father Is Son Then
    Console.Write("Yes, i'm a son") ' this is executed '
End If

您必须将其转换为Son:

If TypeOf father Is Son Then
    Dim son = DirectCast(father, Son)
End If

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 2014-08-27
    相关资源
    最近更新 更多