Istruzione Property
Una proprietà, chiamata anche campo o attributo, caratterizza un determinato oggetto o un pezzo di informazione. Le proprietà possono essere usate per controllare l'accesso ai dati. È pratica comune quella di inserire istruzioni al momento dell'impostazione o della lettura delle proprietà. Il codice, a seconda delle routine, può variare da una semplice istruzione fino ad un contesto complesso. Nei casi in cui ciò è necessario, l'uso delle istruzioni Get, Let o Set assicura la congruenza delle proprietà.
Questa istruzione richiede che Option Compatible sia inserito nel modulo prima della parte eseguibile del programma.
[Private | Public] Property Get name[char | As typename]
End Property
[Private | Public] Property [Let | Set] name[char] [([Optional [ByRef | ByVal]]value[char | As typename])] [As typename]
End Property
name: il nome della proprietà.
argument: valore da passare alla routine che imposta Property.
Le routine di impostazione di Property spesso usano un solo argomento. Comunque sono accettati anche argomenti multipli.
Esempi
Option Compatible
Sub Main
ProductName = "Office"
Print ProductName ' visualizza "LibreOffice"
End Sub
Private _office As String
Property Get ProductName As String
ProductName = _office
End Property
Property Let ProductName(value As String)
_office = "Libre"& value
End Property
In assenza di Property Let o Property Set, Property Get aiuta a definire delle informazioni protette, che non possono essere modificate per errore da un modulo esterno:
Option Compatible
Public Property Get PathDelimiter As String ' variabile di sola lettura
Static this As String
If this = "" Then : Select Case GetGuiType()
Case 1 : this = ";" ' Windows
Case 4 : this = ":" ' Linux o macOS
Case Else : Error 423 ' Proprietà o metodo non definito: PathDelimiter
End Select : End If
PathDelimiter = this
End Property ' PathDelimiter di sola lettura
Sub Main
PathDelimiter = "una frase" ' non fa niente
End Sub
Usate Let o Set se gestite servizi UNO od oggetti di classe:
Option Compatible
Sub Main
'Set anObject = CreateUnoService( "com.sun.star.frame.Desktop" )
anObject = CreateUnoService( "com.sun.star.frame.Desktop" )
Print anObject.SupportedServiceNames(0) ' displays "com.sun.star.frame.Frame"
End Sub
Property Get anObject As Object
Set anObject = _obj
End Property
Private _obj As Object
'Property Set anObject(value As Object)
'Set _obj = value.CurrentFrame
'End Property
Property Let anObject(value As Object)
Set _obj = value.CurrentFrame
End Property