如何访问在C#中的一类形式的方法和控制? [英] How to access form methods and controls from a class in C#?

查看:100
本文介绍了如何访问在C#中的一类形式的方法和控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个C#程序,而现在我有一个表格和几个班。我希望能够访问某些控件(如文本框)从我的课。当我试图改变在文本框中的文本从我的班,我得到了以下错误:

I'm working on a C# program, and right now I have one Form and a couple of classes. I would like to be able to access some of the Form controls (such as a TextBox) from my class. When I try to change the text in the TextBox from my class I get the following error:

需要一个对象引用非静态字段,方法或属性Project.Form1.txtLog

An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog'

我怎么能访问在 Form1.cs的从我的一个类的方法和控制?

How can I access methods and controls that are in Form1.cs from one of my classes?

推荐答案

您试图访问类,而不是对象。这种说法可能会造成混淆初学者,但您有效地试图通过你的房子的计划拿起门打开你家的门。

You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.

如果你其实想直接从类访问窗体组件(你没有),你会使用实例化表单变量。

If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.

根据你想要去你会要么发送控制或任何文本的方法在你的类如:

Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg

public void DoSomethingWithText(string formText)
{
   // do something text in here
}

或你的窗体类暴露的属性和设置格式的文本在那里 - 例如

or exposing properties on your form class and setting the form text in there - eg

string SomeProperty
{
   get 
   {
      return textBox1.Text;
   }
   set
   {
      textBox1.Text = value;
   }
}

这篇关于如何访问在C#中的一类形式的方法和控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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