【发布时间】:2012-01-21 19:39:12
【问题描述】:
我正在开发与外部设备通信的软件。设备需要一组初始化值(calibrationData)。这些校准数据因设备的不同而不同。在第一个版本中,用户可以选择calibrationData,因此用户可能会意外加载在不同部件上获得的calibrationData。该设备可以工作,但测量不正确。 我有
public Instrument(CalibrationData calibration)
{
_camera = new Camera();
_driver = new Driver();
if (_camera.GetUniqueId() != calibration.GetCameraUniqueId())
throw new WrongCalibrationException("Calibration file was obtained on different equipment.");
//Don't write anything here. Exception has to be the last code in the constructor.
}
然后在其他地方
try
{
instrument = new Instrument(calibration);
}
catch (WrongCalibrationException e)
{
MessageBox.Show("You tried to load calibration obtained on different device.");
}
在连接到设备之前,我无法检查 ID。
这个问题实际上包括两个问题。
我的解决方案正确吗?我想自动测试正确校准的使用情况,而不是依赖程序员使用我的代码调用另一种方法(类似于 Instrument.AreYouProperlyCalibrated())
在构造函数末尾抛出异常时,对象是否正确构造?我有点担心 C# 在构造函数完成后会做一些笨拙的事情,如果 ctor 抛出异常,这可能会有所不同。
谢谢
【问题讨论】:
-
Marc 和 Yuriy 几乎涵盖了我的所有想法。我只是补充一点,即使构造函数尚未完全完成,您为该类拥有的任何终结器仍将运行,因此请注意终结器中的这一点(无论如何您似乎都没有)。
标签: c# exception constructor