2011-06-26 12 views
1

オブジェクトリファレンスがオブジェクト43の行に設定されていないため、Webを検索してその答えを見つけることができません。私はC#とプログラミング全般に慣れていないし、学習しようとしています。いくつかのいずれかが私を助けることができるかどうかは、私はそれがB1/B2参照のいずれかに障害が発生していますと仮定していC#オブジェクトリファレンスがオブジェクトのインスタンスに設定されていません

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; 
using System.IO; 
using System.Runtime.Serialization.Formatters.Binary; 

namespace test 
{ 
    public partial class Form1 : Form 
    { 
     [Serializable] 
     public class ore 
     { 
      public float Titan; 
      public float Eperton; 
     } 

     ore b1 = null; 
     ore b2 = null; 

     public Form1() 
     { 
      InitializeComponent(); 

      ore b2 = new ore(); 
      ore b1 = new ore(); 
     } 

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 
      float tempFloat; 

      if (float.TryParse(textBox1.Text, out tempFloat)) 
      { 
       b1.Titan = tempFloat; //line 43; where error happens 
      } 
      else 
       MessageBox.Show("uh oh"); 
     } 

     private void textBox2_TextChanged(object sender, EventArgs e) 
     { 
      float tempFloat; 
      if (float.TryParse(textBox1.Text, out tempFloat)) 
      { 
       b2.Eperton = tempFloat; 
      } 
      else 
       MessageBox.Show("uh oh"); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      List<ore> oreData = new List<ore>(); 
      oreData.Add(b1); 
      oreData.Add(b2); 

      FileStream fs = new FileStream("ore.dat", FileMode.Create); 
      BinaryFormatter bf = new BinaryFormatter(); 
      bf.Serialize(fs, oreData); 
      fs.Close(); 
     } 
    } 
} 
+1

ライン43の上には何ですか? – ChrisBint

+1

b1.Titan = tempFloat;行43です – doc

+0

これは完全なコードではありません...それは動作するはずです。編集:くそー、それを逃した。 – Vercas

答えて

6

素晴らしいことです。

ore b1 = null; 
ore b2 = null; 

ここでは、ここでは、そのメソッド呼び出しのための2つのローカル変数を宣言しているクラスのための2つのプライベート変数

ore b2 = new ore(); 
ore b1 = new ore(); 

を宣言しています。元の変数は変更していません。それを変更します。

b2 = new ore(); 
b1 = new ore(); 
+0

良いキャッチです。不思議に思っていた。 – Femaref

+0

このような悪名高い小さな間違い... – Vercas

+0

大丈夫ですが、エラーはなくなりました。私は新しい問題があるが、ボタンは鉱石をリストし、それをプログラムディレクトリのore.datというファイルに書き込むことになっている。私はプログラムを実行し、保存ボタンを押したが、私のプロジェクトディレクトリに新しいファイルはありませんか? – doc

5

あなたはフィールドb1を割り当てることはありません。コンストラクタで割り当てるb1はローカル変数です。これに、コンストラクタのコードを変更します。これに

b2 = new ore(); 
b1 = new ore(); 
3

変更あなたのコンストラクタを:

public Form1() 
    { 
     InitializeComponent(); 

     b2 = new ore(); 
     b1 = new ore(); 
    } 
関連する問題