问题
plan
im sure this question must have been answered somewhere because its pretty basic, but unfortunately I havent found the answer ...
My plan is to create a simple log function that uses a RichTextField as an output and implements functionalities like Add, AddLine, RemoveLine, ReplaceLine, ...
what doesnt work
whenever i try to access the RichTextBox object from within the log Class, i get a "is nothing" exception.
my approach
the idea was to store a reference to the RichTextBox in the class itsself, that is passed on creating a new class instance:
Public Class Log
Dim _logBox As RichTextBox
Public Sub New(ByRef logBox As RichTextBox)
_logBox = logBox
End Sub
Public Sub AddLine(ByVal text As String)
Me.Add(text)
_logBox.AppendText(Environment.NewLine)
End Sub
End Class
And in my Form class, a RichTextBox is created at startup and passed to the log Class:
Public Class Form1
Dim log As New Log(RtbxLog) ' RtbxLog: RichTextBox object created on form
[on some button click event]
log.AddLine("entry with new line") ' THIS CAUSES "nothing" EXCEPTION
End Class
回答1:
RtbxLog isn't initialized until the New is called. This is usually done during InitializeComponent(). I suggest you create your log after InitializeComponent is called (in the new).
Also, might I suggest you create your own control (that inherit from RichTextBox) instead. Or an other option is that your log class only store the information and the form takes care of display it in the textbox.
来源:https://stackoverflow.com/questions/52206783/vbnet-reference-a-form-object-from-a-class