问题描述
限时送ChatGPT账号..如何在 form1.cs 文件中的另一个自定义类中引用 TextBox
对象(比如 textBox1)?
How can I reference a TextBox
object(say textBox1) in another custom class in form1.cs file?
在myclass
中,我写了textBox1
,但是intelliSense 没有向我推荐它.将私有更改为公共并不能解决问题.
In myclass
, I've written textBox1
, but intelliSense didn't suggest it to me. Changing private to public doesn't solve it.
这里是form1.cs的示例代码
Here is the sample code of form1.cs
namespace Calculator {
public partial class Form1: Form {
public Form1() {
// InitializeComponent();
}
class myclass {
// What can I do to make texbox1 show up in intelliSense here?
// textBox1
}
public System.Windows.Forms.TextBox textBox1;
}
}
推荐答案
如果你想在 myClass
的范围内直接引用它,那么将它声明为静态的.
If you want to reference it directly in the scope of myClass
, then declare it as static.
或者你需要一个 Form1
的实例,但是这不允许你在类定义范围内声明对它的引用,你需要实例化 Form1
的实例code> 在构造函数(或类型初始值设定项)中,您可以将其分配给 myClass
的成员.
Or you would need an instance of Form1
, but that won't allow you declare a reference to it in the class definition scope, you need to instantiate the instance of Form1
in constructor(or type initializer) that you can assign it to the member of myClass
.
namespace Calculator {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}
class myclass {
TextBox textBox3=Form1.textBox1;
TextBox textBox4;
Form1 form1;
public myclass() {
form1=new Form1();
textBox4=form1.textBox2;
}
}
static public System.Windows.Forms.TextBox textBox1;
public System.Windows.Forms.TextBox textBox2;
}
}
<小时>
更新:
关于Form1
的当前实例,下面是在实例化myclass
时传递当前实例的多种方式之一>
For the concerning of current instance of Form1
, following is one of the various ways to pass the current instance when instantiate myclass
namespace Calculator {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
textBox1=textBox2; // demonstration for "static make sense"
var x=new Form1.myclass {
form1=this
};
// now x.textBox3 is reference to textBox2
}
public class myclass {
TextBox textBox3=Form1.textBox1;
TextBox textBox4;
internal Form1 form1;
public myclass() {
// form1=new Form1();
textBox4=form1.textBox2;
}
}
static public System.Windows.Forms.TextBox textBox1;
public System.Windows.Forms.TextBox textBox2;
}
}
这篇关于文本框对象参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论