I have the following statement, I want to turn it into a Public Shared Function :
If isEmployee Then
Dim employeeInstance As New Employee
employeeInstance = GetEmployee开发者_JAVA技巧InstanceByUserId(userId)
Return employeeInstance
Else
Dim studentInstance As New Student
studentInstance = GetStudentInstanceByUserId(userId)
Return studentInstance
End If
Public Shared Function GetWorkerInstance(Byval isEmployee as Boolean) As ...(not sure what to write here)...
There two possible return Type. I'm not sure what I should declare for the function return type.
Any suggestion? Thank you.
This would be easiest if both the Employee
and Student
classes derived from one parent (either a base class or interface), then you could use that as your return type.
You can't declare different return types on the one function and you will not be able to create overrides that return different types, as the method signature resolution does not consider return types.
Generic
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
精彩评论