[英]C# Object reference not set to an instance of an object
我得到的对象引用没有设置为第43行的对象实例,我无法弄清楚为什么,我搜索网络,似乎无法找到答案。 我是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();
}
}
}
我假设它在任何b1 / b2引用上都失败了。
ore b1 = null;
ore b2 = null;
在这里,您要为您的班级声明两个私有变量
ore b2 = new ore();
ore b1 = new ore();
在这里,您为该方法调用声明了两个局部变量。 你没有改变原始变量。 将其更改为:
b2 = new ore();
b1 = new ore();
你永远不会分配字段b1
。 您在构造函数中分配的b1
是局部变量。 将构造函数中的代码更改为:
b2 = new ore();
b1 = new ore();
将构造函数更改为:
public Form1()
{
InitializeComponent();
b2 = new ore();
b1 = new ore();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.