我已经编写了以下代码来在VB.NET中实现它:
Public Class TBdata
Public txtBox() As TextBox = {Form1.TextBox1, Form1.TextBox2, Form1.TextBox3, Form1.TextBox4}
Public aTextBoxes(3) As String
Public Sub DataToArray()
For i As Integer = 0 To 3
aTextBoxes(i) = txtBox(i).Text
Next
End Sub
End Class
'On the Form, to capture all entries in the text boxes
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim d As TBdata = New TBdata()
d.DataToArray()
Dim msg As String = ""
For i As Integer = 0 To 3
msg = msg & d.aTextBoxes(i) & " : "
Next
MessageBox.Show(msg)
End Sub
现在,为什么在C#中无法做到这一点?
class TBdata
{
public string[] aTextBoxes = new string[3];
public TextBox[] txtBox = new TextBox[] { Form1.textBox1, Form1.textBox2, Form1.textBox3, Form1.textBox4 };
public void DataToArray()
{
for (int i = 0; i < 4; i++)
{
aTextBoxes(i) = txtBox(i).Text;
}
}
}
答案 0 :(得分:3)
问题在于:
public TextBox[] txtBox = new TextBox[] { Form1.textBox1, Form1.textBox2, Form1.textBox3, Form1.textBox4 };
如果您在课程中引用Windows表单,请Form1
class TextBoxData
{
public string[] aTextBoxes = new string[3];
public TextBox[] TextBoxes { get; private set;}
public TextBoxData(Form1 form)
{
this.TextBoxes = new TextBox[] { form.textBox1, form.textBox2, form.textBox3, form.textBox4 };
}
public void DataToArray()
{
for (int i = 0; i < TextBoxes.Length; i++)
{
aTextBoxes[i] = TextBoxes[i].Text;
}
}
// ...
。Visual Basic will automatically create a default instance C#不会创建这个“自动”实例,因此您需要将实例显式传递给表单的构造函数,并从该实例加载文本框。
{{1}}
答案 1 :(得分:0)
在您的c#代码中,您的类TBData似乎是私有的。可见关键字不存在且c#默认为private,因此即使您添加正确的using语句以包含TBData命名空间,或者如果您在其他文件或同一命名空间中编写其他内容,您将永远无法实例化类型的对象TBDATA。
同样在c#的代码示例中,您使用括号来访问数组中某个索引处的对象,这是VB的表示法。在c#索引中使用方括号[]访问,括号是为方法调用保留的。