简体   繁体   English

如何使用 Object 类型变量访问 class 的属性?

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

I have declared a "variable" of type OBJECT.我已经声明了一个 OBJECT 类型的“变量”。 I have also declared a class named TEST which has a property "name".我还声明了一个名为 TEST 的 class ,它有一个属性“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".我的理解是,在语句variable = New test()中,编译器正在创建 class TEST 的新实例,并将该新创建实例的引用/内存地址存储在“变量”中。 The idea is that an object type of variable should be able to store any type of data or its reference.这个想法是 object 类型的变量应该能够存储任何类型的数据或其引用。 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?当对实例的引用存储在 object 类型变量中时,有人可以解释为什么以及如何访问该属性吗?

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.因为 Object 没有name属性,并且(在外部)您的变量看起来像 Object。 If you want it to look like Test you'll have to cast it:如果您希望它看起来像 Test ,则必须强制转换它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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