【发布时间】:2015-04-10 09:07:29
【问题描述】:
我正在使用代码来实现硬件测试系统,其中涉及与多个台式仪器的通信。当我实例化这些仪器之一的实例时,构造函数会尝试打开与仪器的通信会话。如果失败,我可以抛出各种错误,但我想做的是让仪器对象默认为虚拟或模拟模式,其中没有进行实际通信但我仍然可以运行我的代码。
现在我拥有从基类继承的一种类型的所有工具。我已经向执行这些调试功能的基类添加了虚拟方法,但我坚持采用一种干净的方式在创建时修改派生对象,以便在通信会话失败时实现基类方法。
理想的解决方案是让构造函数(技术上是 new 关键字)返回基类的实例而不是派生类,但我已经进行了大量搜索,但这似乎是不可能的.
我可以向派生类添加一个属性以用作布尔标志,派生类中的每个方法都针对该标志进行测试,如果为真则调用基类方法,但我希望找到一个更优雅的解决方案不需要几百个 if 语句和严重的 base.Stuff() 调用。
我有几十个方法和一些仪器以这种方式继承,因此不需要显式更改每个覆盖方法的解决方案将有很长的路要走。
public abstract class BaseInstrument
{
public string Address;
protected MessageBasedSession MbSession;
public virtual string Identify()
{
return "Debugging mode, fake identity";
}
}
public class SpecificInstrument : BaseInstrument
{
public SpecificInstrument(string address)
{
Address = address;
try
{
MbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(Address);
}
catch
{
// Return an object modified in such a way that it invokes base class virtual methods
// instead of method overrides.
// Constructor has no return value (that comes from the new keyword) so I can't
// just return an instance of the base class...
}
}
public override string Identify()
{
return ActualInstrumentRead();
}
// ...
}
public class Program
{
public static void Main()
{
SpecificInstrument instr = new SpecificInstrument(ipAddress);
Console.WriteLine(instr.Identify()); // Would like to print the debug case if eg. my LAN is down
}
}
我觉得我可能错过了一个明显的解决方案,但我一直在摸索几个小时。
【问题讨论】:
-
如果你引用基本关键字而不是这个