我已经从另一个类中实例化了一个对象,以便使用该类的属性。在按钮事件中一切正常,但是,在按钮事件之外我得到一个错误,告诉我我的实例化对象被用作类型。如果我使用相同的代码并将其剪切并粘贴到按钮事件中,我不会收到错误消息。我不明白发生了什么以及为什么。该对象是实例化的,无论它是在按钮事件的内部还是外部,为什么它不在按钮事件之外工作?一旦表单打开,我需要从另一个表单自动填充这两个标签字段,而不是单击按钮时。
这是我的代码:
public partial class MeasurementsForm : Form
{
private MeasurementsBOL busObject = new MeasurementsBOL();
//autofill bodyfat and body weight from nutrition form when form opens
busObject.BodyFatB4 = double.Parse(lblBodyFatB4FromNutrition.Text);
busObject.BodyWeightB4 = double.Parse(lblWeightB4FromNutrition.Text);
//default constructor
public MeasurementsForm()
{
InitializeComponent();
busObject.InitializeConnection();
}
//event handler for B4 input data
private void btnEnterMeasurementsB4_Click(object sender, EventArgs e)
{
//convert input data and assign to variables
busObject.ChestMeasurementB4 = double.Parse(txtChestB4.Text);
busObject.WaistMeasurementB4 = double.Parse(txtWaistB4.Text);
busObject.HipsMeasurementB4 = double.Parse(txtHipsB4.Text);
busObject.RightThighB4 = double.Parse(txtRightThighB4.Text);
busObject.LeftThighB4 = double.Parse(txtLeftThighB4.Text);
busObject.RightArmB4 = double.Parse(txtRightArmB4.Text);
busObject.LeftArmB4 = double.Parse(txtLeftArmB4.Text);
//call method to save input data
busObject.SaveB4Data();
//clear text boxes of data
this.txtChestB4.Clear();
this.txtWaistB4.Clear();
this.txtHipsB4.Clear();
this.txtRightThighB4.Clear();
this.txtLeftThighB4.Clear();
this.txtRightArmB4.Clear();
this.txtLeftArmB4.Clear();
//close form
this.Close();
}
以下是MeasurementsBOL类的两个属性。虽然我没有显示它,但该对象已被实例化:
//properties for variables
public double BodyFatB4
{
get { return bodyFatB4; }
set { bodyFatB4 = nutritionObject.BodyFatStart;}
}
public double BodyWeightB4
{
get { return bodyWeightB4; }
set { bodyWeightB4 = nutritionObject.BodyWeight; }
}
答案 0 :(得分:3)
此代码不在任何方法,构造函数等中:
private MeasurementsBOL busObject = new MeasurementsBOL();
//autofill bodyfat and body weight from nutrition form when form opens
busObject.BodyFatB4 = double.Parse(lblBodyFatB4FromNutrition.Text);
busObject.BodyWeightB4 = double.Parse(lblWeightB4FromNutrition.Text);
有一个变量声明很好,但你不能只添加那样的额外语句。幸运的是,您可以使用object initializer:
private MeasurementsBOL busObject = new MeasurementsBOL()
{
BodyFatB4 = double.Parse(lblBodyFatB4FromNutrition.Text),
BodyWeightB4 = double.Parse(lblWeightB4FromNutrition.Text)
};
基本上,类型只能包含诸如字段声明,构造函数声明,属性声明,方法声明等成员。它不能只包含语句。