简体   繁体   中英

Casting in VB.NET

I would like to be able to cast a value dynamically where the type is known only at runtime. Something like this:

myvalue = CType(value, "String, Integer or Boolean")

The string that contains the type value is passed as an argument and is also read from a database, and the value is stored as string in the database.

Is this possible?

 Dim bMyValue As Boolean
 Dim iMyValue As Integer
 Dim sMyValue As String 
 Dim t As Type = myValue.GetType


 Select Case t.Name
     Case "String"
        sMyValue = ctype(myValue, string)
     Case "Boolean"
        bMyValue = ctype(myValue, boolean)
     Case "Integer"
        iMyValue = ctype(myValue, Integer)
 End Select

It's a bit hacky but it works.

Sure, but myvalue will have to be defined as of type Object , and you don't necessarily want that. Perhaps this is a case better served by generics.

What determines what type will be used?

This is the shortest way to do it. I've tested it with multiple types.

Sub DoCast(ByVal something As Object)

    Dim newSomething = Convert.ChangeType(something, something.GetType())

End Sub

Well, how do you determine which type is required? As Joel said, this is probably a case for generics. The thing is: since you don't know the type at compile time, you can't treat the value returned anyway so casting doesn't really make sense here.

Maybe instead of dynamically casting something (which doesn't seem to work) you could use reflection instead. It is easy enough to get and invoke specific methods or properties.

Dim t As Type = testObject.GetType()
Dim prop As PropertyInfo = t.GetProperty("propertyName")
Dim gmi As MethodInfo = prop.GetGetMethod()
gmi.Invoke(testObject, Nothing)

It isn't pretty but you could do some of that in one line instead of so many.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM