Stateless programmering og shared methods
Kig på følgende klasse:Public Class DataTextFile
Private Shared file As System.IO.FileInfo
Private Shared valuepairs As New System.Collections.Specialized.ListDictionary
Private Shared Sub ReadFile()
If (file Is Nothing) Or (Not file.Exists) Then
Throw New System.IO.FileNotFoundException("File not specified, or does not exist when trying to read file contents in DataTextFile class.")
End If
Dim s As System.IO.StreamReader = file.OpenText
Dim l As String = s.ReadLine
Do While Not l Is Nothing
Dim t() As String = l.Split("=")
If Not t.Length = 2 Then Throw New ArgumentOutOfRangeException("Data file had illegal values when trying to read data file in DataTextFile class.")
valuepairs.Add(t(0), t(1))
l = s.ReadLine
Loop
End Sub
Public Shared Sub SetInputFile(ByVal filename As String)
file = New System.IO.FileInfo(filename)
End Sub
Public Shared Sub SetInputFile(ByVal inputfile As System.IO.FileInfo)
file = inputfile
End Sub
Public Shared ReadOnly Property InputFile() As System.IO.FileInfo
Get
Return file
End Get
End Property
Public Shared ReadOnly Property GetValue(ByVal key As String) As String
Get
ReadFile()
Return valuepairs(key)
End Get
End Property
End Class
Hvis jeg i en windows-applikation benyttede SetInputFile-metoden ved programopstart, kunne jeg være temmelig sikker på, at den shared variabel file ville forblive det samme gennem hele kørslen af programmet.
Hvis jeg på en aspx-side benytter SetInputFile-metoden, så kan jeg vel ikke være så sikker længere, hvis siden skifter...eller hvad? Nu har Microsoft jo gjort meget for at gøre ASP.NET mindre stateless... så hvad kan man forvente?
