vb.net untyped arguments
Is it possible to have an argument of any type? Here's what i mean:
some_function(argument)
if (argument type is string)
do something with a string
else if (argument type is datarow)
do something with a data row
...
I've found something abou开发者_如何学运维t generics, but i'm not sure if it's what i want.
You can totally do it like this:
Sub DoSomething(ByVal arg As Object)
If TypeOf arg Is TypeX Then
DoSomethingX(DirectCast(arg, TypeX)
ElseIf TypeOf arg Is TypeY Then
DoSomethingY(DirectCast(arg, TypeY))
End If
End Sub
But: at least first ask yourself if you're trying to do what should really be done with inheritance and polymorphism.
That's a big word for basically this:
Public MustInherit Class BaseType
Public MustOverride Sub DoSomething()
End Class
Public Class TypeX
Inherits BaseType
Public Overrides Sub DoSomething()
' Whatever TypeX does. '
End Sub
End Class
Public Class TypeY
Inherits BaseType
Public Overrides Sub DoSomething()
' Whatever TypeY does. '
End Sub
End Class
It looks like a lot of typing, but then down the road any time you have an object of type BaseType
, instead of a bunch of If
/ElseIf
checks, you just do:
arg.DoSomething()
Might not be the solution in your case. Just wanted to point out that this exists, and might be a better solution to your problem (hard to say without details).
one way is that you can use base type. Set the argument as Object.
some_function(argument as Object)
if (argument type is string)
do something with a string
else if (argument type is datarow)
do something with a data row
Just use overloading. Create methods that have the same name but different argument lists. Visual Basic .NET figures out which method to call during compile based on the parameter types that you pass.
Sub some_function(ByVal argument As String)
End Sub
Sub some_function(ByVal argument As DataRow)
End Sub
精彩评论