VBnet:引用类中的表单对象 [英] VBnet: Reference a form object from a class

查看:62
本文介绍了VBnet:引用类中的表单对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

计划

我肯定一定在某个地方回答了这个问题,因为它很基本,但是很遗憾,我还没有找到答案...

im sure this question must have been answered somewhere because its pretty basic, but unfortunately I havent found the answer ...

我的计划是创建一个简单的日志函数,该函数使用RichTextField作为输出并实现诸如Add,AddLine,RemoveLine,ReplaceLine等功能.

My plan is to create a simple log function that uses a RichTextField as an output and implements functionalities like Add, AddLine, RemoveLine, ReplaceLine, ...

什么不起作用

每当我尝试从日志类中访问RichTextBox对象时,都会收到无"的异常.

whenever i try to access the RichTextBox object from within the log Class, i get a "is nothing" exception.

我的方法

想法是将对RichTextBox的引用存储在自己的类中,该引用在创建新的类实例时传递:

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

在我的Form类中,在启动时创建了RichTextBox并将其传递给日志类:

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

推荐答案

在调用New之前,RtbxLog不会初始化.这通常是在InitializeComponent()期间完成的.我建议您在调用InitializeComponent之后(在新版本中)创建日志.

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).

此外,我是否建议您创建自己的控件(继承自RichTextBox).或者另一个选择是您的日志类仅存储信息,而表单负责在文本框中显示该信息.

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.

这篇关于VBnet:引用类中的表单对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆