引用其他类中的Windows窗体元素 [英] Referencing Windows Form elements in other classes

查看:165
本文介绍了引用其他类中的Windows窗体元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的Windows窗体编程,而我对面的一个问题来了。

I'm very new to Windows Form programming, and I'm coming across a problem.

我有一个窗口的形式, Form1中,一个文本框: tbx_Log

I have a windows form, Form1, with a textbox: tbx_Log.

在另一个类在同一个项目,我想写的东西到日志文本框,但我不能在该类中引用tbx_Log。我怎样才能做到这一点?

In another class in the same project, I want to write something to the log textbox, but I cannot reference tbx_Log in that class. How can I achieve this?

推荐答案

访问内部的其他类的实例(对象)的对象是坏的风格和违反数据封装。一个方法添加到 Form1中

Accessing objects inside other class instances (objects) is bad style and violating data encapsulation. Add a method to Form1:

public void SetLogText(String text)
{
     tbx_Log.Text = text;
}

这方式,您可以通过使用一些其他控制或改变方法的实现记录到以后的文件,而不必修改所有的调用点。应尽量将有类外的代码没有对里面有什么知识。类的实现应该是一个黑匣子对于外界的代码。

This way you can change the implementation of the method by using some other control or logging to a file later, without having to modify all the call sites. Always try to have the code outside the class not to have knowledge about what's inside. The class implementation shall be a "black box" for the outside code.

这篇关于引用其他类中的Windows窗体元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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