我有以下声明,我想把它变成公共共享功能:
If isEmployee Then
Dim employeeInstance As New Employee
employeeInstance = GetEmployeeInstanceByUserId(userId)
Return employeeInstance
Else
Dim studentInstance As New Student
studentInstance = GetStudentInstanceByUserId(userId)
Return studentInstance
End If
公共共享函数GetWorkerInstance(Byval isEmployee as Boolean)As ...(不知道在这里写什么)......
有两种可能的返回类型。我不确定我应该为函数返回类型声明什么。
有什么建议吗?谢谢。
答案 0 :(得分:2)
如果Employee
和Student
类派生自一个父类(基类或接口),那么这将是最简单的,那么您可以将其用作返回类型。
您不能在一个函数上声明不同的返回类型,并且您将无法创建返回不同类型的覆盖,因为方法签名解析不考虑返回类型。
答案 1 :(得分:0)
通用
Private Class foo
Dim s As String = "FOO"
End Class
Private Class bar
Dim s As String = "BAR"
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim o As Object = GetWorkerInstance(True)
If TypeOf o Is foo Then
Stop
Else
Stop
End If
End Sub
Public Shared Function GetWorkerInstance(ByVal isEmployee As Boolean) As Object
If isEmployee Then Return New foo Else Return New bar
End Function