C-style pointer in Visual Basic .NET

后端 未结 2 2006
一个人的身影
一个人的身影 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:39

    There's some issues with your C code, one of them being this:

    int *myNumber=3; //the * means it's a pointer  
    

    You cannot assign a value to a pointer like that, without first allocating memory to it.

    So you would do the following:

    int* myNumber = malloc(sizeof(int));
    *myNumber  = 3;
    free(myNumber);
    

    VB.NET has no notion of pointers. Everything (ie every Object) is a reference, and that's about as close to pointers it will get without using Interop. If you need to do interop there's the IntPtr type which can be used to represent a pointer type.

    Your VB.NET program might look something like this: (forgive me if the syntax isn't exactly correct, it's been a while)

    Sub Main
        Dim myNumber As Integer = 3
        doubleIt(myNumber)
        Console.WriteLine(myNumber)
    End Sub
    
    Sub doubleIt(ByRef val As Integer)
        val *= 2
    End Sub
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题