简体   繁体   中英

How to access properties of a class using Object type variable?

I have declared a "variable" of type OBJECT. I have also declared a class named TEST which has a property "name". My understanding is that in the statement variable = New test() the compiler is creating a new instance of the class TEST and storing the reference/memory address of that newly created instance in "variable". The idea is that an object type of variable should be able to store any type of data or its reference. By that logic using the member accessor operator I should be able to access the property "name" using "variable". But I am unable to. Can someone please explain why and how to access the property when the reference to the instance is being stored in an object type variable?

Module Program
    Sub Main()
        Dim variable As Object
        variable = New test()
        Console.WriteLine("Value: {0}   Type: {1}", variable, variable.GetType())
        'Output is Type: Object_Data_Type.test --> Works
        'However we cannot access the property name of the class TEST through "varibale"
        Console.ReadLine()
    End Sub
End Module

Public Class test
    Public Property name As String
End Class

Because an Object doesn't have a name property, and (on the outside) your variable looks like Object. If you want it to look like Test you'll have to cast it:

Console.WriteLine("Value: {0}   Type: {1}", DirectCast(variable, Test).name, variable.GetType())

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