我正在使用HeadFirst C#Book进行教程。表单本身之前是工作但现在它不是,我不记得我改变了什么。我现在已经多次翻过文本了,它似乎是一个逐字的副本,但它不起作用。我究竟做错了什么?我想问题必须在Form.cs文件中。
这是该课程的代码。
class DinnerParty
{
public const int CostOfFoodPerPerson = 25;
//declare DinnerParty automatic properties
public int NumberOfPeople { get; set; }
public bool HealthyOption { get; set; }
public bool FancyDecorations { get; set; }
// Setup Object Constructor with parameters masking the properties
public DinnerParty(int numberOfPeople, bool healthyOption, bool fancyDecorations)
{
//Set Property Values to parameter values
NumberOfPeople = numberOfPeople;
HealthyOption = healthyOption;
FancyDecorations = fancyDecorations;
}
// Use private methods to access public properties bound to the form.
private decimal CalculateCostOfBeveragesPerPerson()
{
decimal costOfBeveragesPerPerson;
if (HealthyOption)
{
costOfBeveragesPerPerson = 5.00M;
}
else
{
costOfBeveragesPerPerson = 20.00M;
}
return costOfBeveragesPerPerson;
}
protected decimal CalculateCostOfDecorations()
{
decimal costOfDecorations;
if (FancyDecorations)
{
costOfDecorations = (NumberOfPeople * 15.00M) + 50M;
}
else
{
costOfDecorations = (NumberOfPeople * 7.50M) + 30M;
}
return costOfDecorations;
}
//declare read only Cost property to be bound to costLabel control
public decimal Cost
{
get
{
decimal totalCost = CalculateCostOfDecorations();
totalCost += ((CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson) * NumberOfPeople);
if (HealthyOption)
{
totalCost *= .95M;
}
return totalCost;
}
}
}
}
这是表单的代码。
namespace DinnerParty
{
public partial class Form1 : Form
{
DinnerParty dinnerParty;
public Form1()
{
InitializeComponent();
//Initialize DinnerParty object. Initialize DinnerParty party with default form values.
dinnerParty = new DinnerParty((int) numericUpDown1.Value, healthyBox.Checked , fancyBox.Checked);
DisplayDinnerPartyCost();
}
// Bind form controls to DinnerParty Properties
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
dinnerParty.NumberOfPeople = (int)numericUpDown1.Value;
DisplayDinnerPartyCost();
}
private void fancyBox_CheckedChanged(object sender, EventArgs e)
{
dinnerParty.FancyDecorations = fancyBox.Checked;
DisplayDinnerPartyCost();
}
private void healthyBox_CheckedChanged(object sender, EventArgs e)
{
dinnerParty.HealthyOption = healthyBox.Checked;
DisplayDinnerPartyCost();
}
private void DisplayDinnerPartyCost()
{
decimal Cost = dinnerParty.Cost;
costLabel.Text = Cost.ToString("c");
}
}
}
答案 0 :(得分:0)
代码中的以下行可能有误。我没有看到任何课程DinnerParty2。将其更改为DinnerParty
dinnerParty = new DinnerParty2((int) numericUpDown1.Value, healthyBox.Checked , fancyBox.Checked);
答案 1 :(得分:0)
根据评论,如果您要复制代码,请确保在设计器中再次连接事件处理程序,或手动:
healthyBox.CheckedChanged += healthyBox_CheckedChanged;
因为复制和粘贴控件时,不包括事件处理程序。