C-style pointer in Visual Basic .NET

后端 未结 2 2011
一个人的身影
一个人的身影 2021-01-23 12:19

I have been investigating C-style pointers in Visual Basic .NET for a while now. I have come across http://support.microsoft.com/kb/199824?wa=wsignin1.0 but I have no idea if th

2条回答
  •  无人共我
    2021-01-23 12:49

    In .NET, there are two kinds of object types. There are reference types (Class) and there are value types (Structure). Instead of deciding, for each variable, whether or not that variable is a pointer, in .NET, all reference type objects are always treated like pointers and all value type objects are not. So, for instance:

    'Create one object of each type
    Dim builder As New StringBuilder()  'Reference type
    Dim size As Integer  'Value type
    
    'Make a "copy" of each
    Dim copyBuilder As StringBuilder = builder
    Dim copySize As Integer = size
    
    'Change the value of the original object
    builder.Append("Test")
    size = 33
    
    'Check if the "copy" changed
    Console.WriteLine("{0} = {1}", builder.ToString(), copyBuilder.ToString())
    Console.WriteLine("{0} <> {1}", size, copySize)
    

    When you run that code, it will output this:

    Test = Test
    33 <> 0
    

    So, as you can see, StringBuilder objects act like pointers whereas Integer objects do not. However, as Tony pointed out, even with value types, you can pass a value "by reference" to a method. When a method specifies that one of its parameters is ByRef, as opposed to ByVal, it means that the method may change the value of the variable internally and the change will affect the variable in the calling code.

    Also, you may want to do some research into boxing and unboxing.

提交回复
热议问题