简体   繁体   中英

Object Reference casting vb.net

I have no idea on how to cast an object that type was 'Object' to a user defined class type.

I have a private instance variable:

Private studyType as Object

What i need to do is to instantiate this object from an event handling method. And no, not to instance new Object() .

Basically it would look like this:

studyType = new VCEOnly()

However, I am only allowed to use the Object class subs and functions as the type was defined as Object . So i need to cast it to VCEOnly class type so i can access its subs and functions.

Basically, studyType needs to be casted from Object to VCEOnly . I am not allowed to pre-define studyType as VCEOnly when declared.

you can also use:

dim studyType as Object = new VCEOnly()    

...

dim studyTypeVCE as VCEOnly = nothing
if trycast(studytype,VCEOnly) IsNot Nothing then
   studyTypeVCE = DirectCast(studytype,VCEOnly)
   '... do your thing
end if

the if statement checks if the object can be casted to the wanted type and if so variable of type VCEOnly will be filled in with a cast of studytype.

Use CType to cast an object from one type to another

Something like this should do it:

Dim studyType as Object
Dim studyTypeVCE as New VCEOnly
studyTypeVCE = Ctype(studyType,VCEOnly)

or you can just do this:

With CType(studyType, VCEOnly)
    .SomeVCEOnlyProperty = "SomeValue"
End With

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