【发布时间】:2011-01-24 07:50:17
【问题描述】:
我正在编写一些错误检查并尝试使用布尔数组在元素中存储真或假,然后我的最终条件解析存储的元素以确定它在 Visual Studio 2008 中是否全部为真。可能有一种更简单的错误检查方法,但不妨学习如何利用数组。这是我到目前为止所拥有的
bool[] checker = new bool[1]; // declared array...I think
private void print_button_Click(object sender, EventArgs e)
{
if (authorbox.Text == "")
{
MessageBox.Show("Author field empty", "Required Entry");
}
else
{
checker[0] = true; // assigning element to array correctly?
}
if (titlebox.Text == "")
{
MessageBox.Show("Title field Empty", "Required Entry");
}
else
{
checker[1] = true;
}
// The part I am having trouble with basically if any of my array elements are
// false don't execute printing. Else go ahead and print.
if ()
{
}
else
{
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
}
【问题讨论】:
-
checker[1] = true;将抛出越界错误:您的数组只有一个元素 (bool[1]),该元素位于索引 0 处(C# 数组索引从 0 开始)。我认为您的意思是checker是一个二元素数组,即bool[] checker = new bool[2];。 -
您的代码有错误。如果您声明一个数组有 1 个索引(新布尔 [1])...它不能有一个检查器 [1]。 [] 中的数字是数组元素的计数或总数。引用它们的实际索引值将从零开始。所以你需要做 bool[] checker = new bool[2];能够做 checker[0] 和 checker[1]