Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VB.Net:父类型中的Byref,但将子类型返回给Byref_.net_Vb.net_Class_Inheritance_Byref - Fatal编程技术网

VB.Net:父类型中的Byref,但将子类型返回给Byref

VB.Net:父类型中的Byref,但将子类型返回给Byref,.net,vb.net,class,inheritance,byref,.net,Vb.net,Class,Inheritance,Byref,在这种情况下,如何保持返回到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) 但如果需要,您可以指定一个子: ' Should return a Son, not a Father Public Sub Save(By

在这种情况下,如何保持返回到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)

但如果需要,您可以指定一个

' Should return a Son, not a Father
Public Sub Save(ByRef obj As Father)
    obj = New Son
End Sub
现在,当您调用
Save
时,您有了一个
而不是

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
您必须将其强制转换才能将其用作子:

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

这应该是一个函数。谷歌“工厂方法模式”了解更多。儿子不一定是父亲,我希望我的不是一段时间。。。你能把它改成函数吗?公共功能保存(ByVal obj作为父亲)作为儿子