我正在学习C#,现在我被动态对象所困(如果有这样的事情)。
我在一个用户窗体上有两个按钮和两个文本框,所以我想做的就是每次单击Button1
实例化一个对象并将其name属性值分配给TextBox1中的任何文本。几个实例之后,我想检索任何已创建对象的名称值(类似MessageBox.Show(obj[int.Parse(TextBox2.text)].name)
)。
代码抛出错误:
System.NullReferenceException:'对象引用未设置为对象的实例。'
TEST[] o;
private void Button1_Click(object sender, EventArgs e)
{
o = new TEST[10];
o[1].name = textBox1.Text;
}
private void Button2_Click(object sender, EventArgs e)
{
MessageBox.Show(o[1].xcount.ToString());
}
我想按对象索引/计数读取特定对象的属性值。
答案 0 :(得分:1)
在这里,您每次都实例化Test
类的数组。创建一个名为Name的类(而不是动态类),该属性将在每次单击按钮时存储textbox1
的值。
单击Button2
Test[] testArray = new Test[10];
int index = 0;
private void Button1_Click(object sender, EventArgs e)
{
if(index < 10) //To avoid ArrayIndexOutOfBound error
{
testArray[index++] = new Test() { Name = textBox1.Text };
}
}
private void Button2_Click(object sender, EventArgs e)
{
//Read Name of first element in an array
string firstName = testArray.FirstOrDefault()?.Name;
MessageBox.Show(firstName);
}
public class Test
{
public string Name { get; set; }
}
答案 1 :(得分:0)
您选择使用数组是正确的方法之一。
首先,应将数组的初始化移到方法外,以免每次按按钮1时都不会创建新的数组(因此会丢弃旧对象)。
TEST[] o = new TEST[10];
private void Button1_Click(object sender, EventArgs e)
{
// ...
}
接下来,添加一个变量,该变量指示将下一个元素添加到数组的位置:
int next = 0;
TEST[] o = new TEST[10];
private void Button1_Click(object sender, EventArgs e)
{
// ...
}
在Button1_Click
内,您需要创建一个TEST
中name
的{{1}}对象,将其分配给textBox1.Text
,并递增{{1} },以便可以插入下一个元素。
o[next]
尝试确定如何实现next
。
很显然,该程序只能存储固定数量的o[next] = new TEST { name = textBox1.Text };
next++;
对象。如果要存储未知数量的对象,则需要Button2_Click
:
TEST
答案 2 :(得分:0)
创建数组TEST
后,它将包含10个位置,所有位置均包含null
。您必须首先创建TEST
对象
o = new TEST[10];
// o[1] is null here.
o[1] = new TEST(); // Create object.
o[1].name = textBox1.Text;
或
o = new TEST[10];
TEST test = new TEST();
test.name = textBox1.Text;
o[1] = test;
或者,使用对象初始化程序
o = new TEST[10];
o[1] = new TEST{name = textBox1.Text};
但是请注意,数组索引是从零开始的。也就是说,数组的第一个元素是o[0]
,最后一个是o[9]
。
此外,请注意,您的Button1_Click
方法每次都会创建一个新数组,从而丢弃之前存储的所有值。
答案 3 :(得分:0)
首先,您的Button1_Click确实会重置每次单击的o数组。 您想要做的是将其移到那里,可能是在初始化方法中,或者在构造函数中。全局声明也可以。
second,System.NullReferenceException:“对象引用未设置为对象的实例。”因为尝试访问尚未定义的Array插槽而被抛出。
o = new TEST[10]; //new array here
o[1].name = textBox1.Text; //and then you access slot[1] immediately
您要做的是首先设置插槽[1]。
o[1] = new Test();
为避免将来出现此错误,您需要确保在访问插槽之前已实例化该插槽。
if (slot[i] != null)
{ slot[i].name = "nam"; }
答案 4 :(得分:0)
感谢大家,您的输入帮助我以入门的方式编写了这个很棒的程序: int next = 0; TEST [] o =新的TEST [10]; 私有void Button1_Click(对象发送者,EventArgs e) { o [next] =新的测试{name = textBox1.Text}; next ++; } 私有void Button2_Click(对象发送者,EventArgs e) { MessageBox.Show(o [int.Parse(textBox2.Text)]。name); }