C#对象实例化问题:解决‘未将对象引用设置到对象实例’错误
问题原因与解决方法
你遇到的Object Reference Not Set to an Instance of an Object错误,核心原因是:你只实例化了WaferAlignment对象,但它内部的Coordinates类型属性(比如upper1/upper2)默认是null,直接访问这些null对象的x/y属性就会触发空引用异常。另外注意你的代码里用了calc.lower1,但WaferAlignment类中并没有定义lower1属性,这大概率是笔误,应该是upper1或者你需要补充定义lower1属性。
下面提供三种常用的实例化方式:
方式一:在WaferAlignment的构造函数中初始化Coordinates
修改WaferAlignment类,添加构造函数,在里面为每个Coordinates属性创建实例:
public class WaferAlignment { public Coordinates upper1 { get; set; } public Coordinates upper2 { get; set; } // 新增构造函数 public WaferAlignment() { upper1 = new Coordinates(); upper2 = new Coordinates(); // 如果需要lower1,先在类里定义,再在这里初始化 // lower1 = new Coordinates(); } }
这样每次创建WaferAlignment对象时,它的upper1/upper2都会自动被实例化,后续直接访问calc.upper1.x就不会报错。
方式二:在MainWindow中手动初始化Coordinates属性
在创建WaferAlignment对象后,手动为其内部的Coordinates属性赋值实例:
public partial class MainWindow : Window { WaferAlignment calc = new WaferAlignment(); public MainWindow() { InitializeComponent(); // 手动初始化upper1和upper2 calc.upper1 = new Coordinates(); calc.upper2 = new Coordinates(); // 如果需要lower1,先在WaferAlignment类里定义,再初始化 // calc.lower1 = new Coordinates(); } public void ButtonCalculate_Click(object sender, RoutedEventArgs e) { try { // 修正笔误,改为upper1(或你实际需要的属性) calc.upper1.x = Convert.ToDouble(Lower_X_TextBox0.Text); calc.upper1.y = Convert.ToDouble(Lower_Y_TextBox0.Text); } catch(Exception ex) { // 建议添加异常捕获逻辑,方便排查问题 MessageBox.Show(ex.Message); } } }
方式三:使用C# 6.0+的属性初始化语法
在定义WaferAlignment的属性时,直接初始化实例,写法更简洁:
public class WaferAlignment { public Coordinates upper1 { get; set; } = new Coordinates(); public Coordinates upper2 { get; set; } = new Coordinates(); // 如果需要lower1: // public Coordinates lower1 { get; set; } = new Coordinates(); }
这种方式和方式一效果类似,无需额外写构造函数,属性会在对象创建时自动初始化。
最后提醒:记得检查代码中的lower1是否是笔误,如果确实需要这个属性,一定要在WaferAlignment类中先定义它,再进行实例化。
内容的提问来源于stack exchange,提问作者Lourdea
相关产品推荐
相关产品推荐

