0

そのクラスのプロパティを使用するために、別のクラスのオブジェクトをインスタンス化しました。ボタンイベント内ではすべて正常に機能しますが、ボタンイベント以外では、インスタンス化されたオブジェクトが型として使用されていることを示すエラーが発生します。これとまったく同じコードを切り取ってボタンイベントに貼り付けても、エラーメッセージは表示されません。何が起こっているのか、そしてその理由がわかりません。オブジェクトは、ボタンイベントの内側または外側にあるかどうかに関係なくインスタンス化されるので、ボタンイベントの外側で機能しないのはなぜですか?ボタンがクリックされたときではなく、フォームが開いたらすぐに、これら2つのラベルフィールドを別のフォームから自動入力する必要があります。

これが私のコードです:

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クラスの2つのプロパティです。表示していませんが、オブジェクトはインスタンス化されています。

//properties for variables
public double BodyFatB4 
{
    get { return bodyFatB4; }
    set { bodyFatB4 = nutritionObject.BodyFatStart;}
}

public double BodyWeightB4 
{ 
    get { return bodyWeightB4; }
    set { bodyWeightB4 = nutritionObject.BodyWeight; }
}
4

1 に答える 1

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);

変数宣言があっても問題ありませんが、そのようなステートメントを追加することはできません。幸い、オブジェクト初期化子を使用できます。

private MeasurementsBOL busObject = new MeasurementsBOL()
{
    BodyFatB4 = double.Parse(lblBodyFatB4FromNutrition.Text),
    BodyWeightB4 = double.Parse(lblWeightB4FromNutrition.Text)
};

基本的に、型にはフィールド宣言、コンストラクター宣言、プロパティ宣言、メソッド宣言などのメンバーのみを含めることができます。ステートメントだけを含めることはできません。

于 2012-04-23T17:26:54.827 に答える