【发布时间】:2025-12-30 14:45:11
【问题描述】:
我正在编写 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");
}
}
}
【问题讨论】:
-
此问题不符合本网站的指南。具体是什么不起作用? FAQ
-
我更新了问题。这更清楚吗?对不起。
-
如果您要复制代码,请确保在设计器中再次连接事件处理程序,或者手动连接,
healthyBox.CheckedChanged += healthyBox_CheckedChanged; -
谢谢!!!这行得通。我知道它必须是简单的!太感谢了!我永远不会找到这个大声笑。