< Day Day Up > |
Fields are variables that are contained within user -defined types. Fields can be given an initial value by assigning an expression to the field in its declaration. Constructors can also be used to initialize fields in structures and classes. The following example shows different methods of declaring and initializing fields. Class Test Public x, y As Integer Public z As Integer = 10 Public a As New Test(10) Public Sub New(ByVal a As Integer) x = a y = a End Sub End Class Fields can be declared ReadOnly , which prevents their values from being changed after they are initialized . Read-only fields can only be assigned a value in a constructor or by an initializer ”outside a constructor, the value of the field is read-only. Class Customer ReadOnly Name As String ReadOnly ZIP As Integer = 98112 Sub New(ByVal Name As String) Me.Name = Name End Sub Sub ChangeName(ByVal Name As String) ' Error: Name is ReadOnly Me.Name = Name End Sub End Class Constants are fields whose values are known at compile time and cannot be changed at runtime. Constants are more efficient than read-only fields because the compiler can substitute the constant value at compile time instead of having to read it at runtime. Enum Color Red Blue Green End Enum Class Control Public BackColor As Color = DefaultColor Const DefaultColor As Color = Color.Red End Class |
< Day Day Up > |