Rediģēt

Kopīgot, izmantojot


Friend (Visual Basic)

Specifies that one or more declared programming elements are accessible only from within the assembly that contains their declaration.

Remarks

In many cases, you want programming elements such as classes and structures to be used by the entire assembly, not only by the component that declares them. However, you might not want them to be accessible by code outside the assembly (for example, if the application is proprietary). If you want to limit access to an element in this way, you can declare it by using the Friend modifier.

Code in other classes, structures, and modules that are compiled to the same assembly can access all the Friend elements in that assembly.

Friend access is often the preferred level for an application's programming elements, and Friend is the default access level of an interface, a module, a class, or a structure.

You can use Friend only at the module, interface, or namespace level. Therefore, the declaration context for a Friend element must be a source file, a namespace, an interface, a module, a class, or a structure; it can't be a procedure.

Note

You can also use the Protected Friend access modifier, which makes a class member accessible from within that class, from derived classes, and from the same assembly in which the class is defined. To restrict access to a member from within its class and from derived classes in the same assembly, you use the Private Protected access modifier.

For a comparison of Friend and the other access modifiers, see Access levels in Visual Basic.

Note

You can specify that another assembly is a friend assembly, which allows it to access all types and members that are marked as Friend. For more information, see Friend Assemblies.

Example

The following class uses the Friend modifier to allow other programming elements within the same assembly to access certain members.

Class CustomerInfo

    Private p_CustomerID As Integer

    Public ReadOnly Property CustomerID() As Integer
        Get
            Return p_CustomerID
        End Get
    End Property

    ' Allow friend access to the empty constructor.
    Friend Sub New()

    End Sub

    ' Require that a customer identifier be specified for the public constructor.
    Public Sub New(ByVal customerID As Integer)
        p_CustomerID = customerID
    End Sub

    ' Allow friend programming elements to set the customer identifier.
    Friend Sub SetCustomerID(ByVal customerID As Integer)
        p_CustomerID = customerID
    End Sub
End Class

Usage

You can use the Friend modifier in these contexts:

Class Statement

Const Statement

Declare Statement

Delegate Statement

Dim Statement

Enum Statement

Event Statement

Function Statement

Interface Statement

Module Statement

Property Statement

Structure Statement

Sub Statement

See also