0 c# variables unassigned-variable
我刚刚开始使用C#,我已经坚持了两个星期这个问题.我有一个主窗体,从类和子类获取值.我的问题是当我尝试创建一个CorporateClass的对象时,VB告诉我我的两个变量(CarSizeInteger和DiscountInteger)是未分配的.我的问题是为什么.我在程序的早期实现了它们.救命!我绝望地被卡住了!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace EX02_CarRentals
{
public partial class RentalForm : Form
{
public RentalForm()
{
InitializeComponent();
}
private void CloseButton_Click(object sender, EventArgs e)
{
Close();
}
private void CalculateButton_Click(object sender, EventArgs e)
{
int DaysInteger, BeginningOdometerInteger, EndingOdometerInteger, CarSizeInteger, DiscountInteger;
if (LicenseTextBox.Text != "")
if (CompactRadioButton.Checked || MidSizeRadioButton.Checked || LuxuryRadioButton.Checked)
{
int.TryParse(DaysRentedTextBox.Text, out DaysInteger);
int.TryParse(BeginningOdometerTextBox.Text, out BeginningOdometerInteger);
if (BeginningOdometerInteger > 0)
{
int.TryParse(EndingOdometerTextBox.Text, out EndingOdometerInteger);
if (EndingOdometerInteger > 0)
{
if (CompactRadioButton.Checked)
CarSizeInteger = (int)CarSize.Compact;
else if (MidSizeRadioButton.Checked)
CarSizeInteger = (int)CarSize.MidSize;
else CarSizeInteger = (int)CarSize.Luxury;
}
{
if (CorporateRadioButton.Checked || InsuranceRadioButton.Checked)
{
if (CorporateRadioButton.Checked)
DiscountInteger = (int)Discount.Corporate;
else if (InsuranceRadioButton.Checked)
DiscountInteger = (int)Discount.Insurance;
//create an instance of the Corporate Class
CorporateClass aCorpRental = new CorporateClass(BeginningOdometerInteger, EndingOdometerInteger, CarSizeInteger, DaysInteger, DiscountInteger);
AmountDueTextBox.Text = (aCorpRental.getAmountDue()).ToString("C");
}
else
{
//create an instance of the Rental Class
RentalRate ARental = new RentalRate(BeginningOdometerInteger, EndingOdometerInteger, CarSizeInteger, DaysInteger);
AmountDueTextBox.Text = (ARental.getAmountDue()).ToString("C");
}
}
}
}
}
}
private void DaysRentedTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
在C#中,您不能在给定值之前使用变量的值,否则您将获得未分配的变量错误.让我们看看为什么你的代码会给你这个.
我会专注于CarSizeInteger.您尝试初始化的位置有三个CarSizeInteger:
if (EndingOdometerInteger > 0)
{
if (CompactRadioButton.Checked)
CarSizeInteger = (int)CarSize.Compact;
else if (MidSizeRadioButton.Checked)
CarSizeInteger = (int)CarSize.MidSize;
else CarSizeInteger = (int)CarSize.Luxury;
}
Run Code Online (Sandbox Code Playgroud)
请注意,这三个任务都包含在if (EndingOdometerInteger > 0)块中.如果EndingOdometerInteger > 0是假的,则不会发生任何分配.因此,当您尝试稍后使用时CarSizeInteger,编译器会检测CarSizeInteger到可能未初始化,这是一个错误.
要避免此错误,您可以提供CarSizeInteger默认值:
int CarSizeInteger = 0;
Run Code Online (Sandbox Code Playgroud)
或者在if语句中添加一个else块来初始化CarSizeInteger:
if (EndingOdometerInteger > 0)
{
// ...
}
else
{
CarSizeInteger = 0;
}
Run Code Online (Sandbox Code Playgroud)
在任何情况下,只需确保在尝试读取其值之前为每个变量赋值.