在if的其他部分添加闭合和开启大括号,就像我在下面做的那样帮助我,而不是在添加它们之前做的事情;
之前:这引起了错误:
protected void btnAdd_Click(object sender, EventArgs e)
{
if (btnAdd.Text == "ADD")
{
CATEGORY cat = new CATEGORY
{
NAME = tbxCategory.Text.Trim(),
TOTALSALEVALUE = tbxSaleValue.Text.Trim(),
PROFIT = tbxProfit.Text.Trim()
};
dm.AddCategory(cat, tbxCategory.Text.Trim());
}
else
// missing brackets - this was causing the error
var c = getCategory();
c.NAME = tbxCategory.Text.Trim();
c.TOTALSALEVALUE = tbxSaleValue.Text.Trim();
c.PROFIT = tbxProfit.Text.Trim();
dm.UpdateCategory(c);
btnSearchCat_Click(btnSearchCat, e);
}
后:在else分支
protected void btnAdd_Click(object sender, EventArgs e)
{
if (btnAdd.Text == "ADD")
{
CATEGORY cat = new CATEGORY
{
NAME = tbxCategory.Text.Trim(),
TOTALSALEVALUE = tbxSaleValue.Text.Trim(),
PROFIT = tbxProfit.Text.Trim()
};
dm.AddCategory(cat, tbxCategory.Text.Trim());
}
else
{
var c = getCategory();
c.NAME = tbxCategory.Text.Trim();
c.TOTALSALEVALUE = tbxSaleValue.Text.Trim();
c.PROFIT = tbxProfit.Text.Trim();
dm.UpdateCategory(c);
}
btnSearchCat_Click(btnSearchCat, e);
}
我同意加括号,它没有任何意义可言申报以这种方式变化。然而,第二个例子中完全无用的变量声明没有问题。没有价值。这仅仅是一个括号问题,没有别的? (顺便说一句,我可以和他一起生活)。 – 2010-03-22 23:58:26
是的。当你包含括号时,你的意图对编译器来说是绝对清楚的,所以它会允许的。 C#编译器不会在没有括号的情况下允许它,因为不清楚您的实际意图是声明无用变量。 – 2010-03-23 00:00:37
但是第二个可能非常有价值 - 例如,如果从具有副作用的方法中检索值。 – 2010-03-23 00:08:49