ByRef vs ByVal Clarification

前端 未结 4 438
悲&欢浪女
悲&欢浪女 2020-11-27 06:51

I\'m just starting on a class to handle client connections to a TCP server. Here is the code I\'ve written thus far:

Imports System.Net.Sockets
Imports Syst         


        
4条回答
  •  抹茶落季
    2020-11-27 07:09

    My understanding has always been that the ByVal/ByRef decision really matters most for value types (on the stack). ByVal/ByRef makes very little difference at all for reference types (on the heap) UNLESS that reference type is immutable like System.String. For mutable objects, it doesn't matter if you pass an object ByRef or ByVal, if you modify it in the method the calling function will see the modifications.

    Socket is mutable, so you can pass any which way you want, but if you don't want to keep modifications to the object you need to make a deep copy yourself.

    Module Module1
    
        Sub Main()
            Dim i As Integer = 10
            Console.WriteLine("initial value of int {0}:", i)
            ByValInt(i)
            Console.WriteLine("after byval value of int {0}:", i)
            ByRefInt(i)
            Console.WriteLine("after byref value of int {0}:", i)
    
            Dim s As String = "hello"
            Console.WriteLine("initial value of str {0}:", s)
            ByValString(s)
            Console.WriteLine("after byval value of str {0}:", s)
            ByRefString(s)
            Console.WriteLine("after byref value of str {0}:", s)
    
            Dim sb As New System.Text.StringBuilder("hi")
            Console.WriteLine("initial value of string builder {0}:", sb)
            ByValStringBuilder(sb)
            Console.WriteLine("after byval value of string builder {0}:", sb)
            ByRefStringBuilder(sb)
            Console.WriteLine("after byref value of string builder {0}:", sb)
    
            Console.WriteLine("Done...")
            Console.ReadKey(True)
        End Sub
    
        Sub ByValInt(ByVal value As Integer)
            value += 1
        End Sub
    
        Sub ByRefInt(ByRef value As Integer)
            value += 1
        End Sub
    
        Sub ByValString(ByVal value As String)
            value += " world!"
        End Sub
    
        Sub ByRefString(ByRef value As String)
            value += " world!"
        End Sub
    
        Sub ByValStringBuilder(ByVal value As System.Text.StringBuilder)
            value.Append(" world!")
        End Sub
    
        Sub ByRefStringBuilder(ByRef value As System.Text.StringBuilder)
            value.Append(" world!")
        End Sub
    
    End Module
    

提交回复
热议问题