在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