Vb.Net scoping question - private fields
I have been looking at a class that has a method that accepts a parameter that is of the same type of the class containing the method.
Public Class test
private _avalue as integer
Public Sub CopyFrom(ByVal from as test)
_avalue = from._avalue
End Sub
End Class
When used in code
a.CopyFrom(b)
It appears that instance "a" has visibility to the private members of the passed in instance "b" and the line
_avalue = from._avalue
runs without error copying the private field from one object i开发者_开发知识库nstance to the other.
Does anyone know if this is by design. I was under the impression that a private field was only accessible by the instance of the object.
The private
scope is related to the type not the instance. So yes, this is by design.
The class test
has knowledge about the private parts of itself, so it can use those parts also on other instances of the same type.
You are writing something similar to to a copy constructor.
Since the copying method/function is being written inside of the same class, it will have access to private variables of any instance of its own class.
精彩评论