【问题标题】:Implement Derived Class as Base on Constructor Exception?基于构造函数异常实现派生类?
【发布时间】: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
    }
}

我觉得我可能错过了一个明显的解决方案,但我一直在摸索几个小时。

【问题讨论】:

  • 如果你引用基本关键字而不是这个

标签: c# casting


【解决方案1】:

您不能从 SpecificInstrument 构造函数返回 BaseInstrument

另一种选择是将这个逻辑放在你创建这个工具的地方:

BaseInstrument instrument;
try {
    instrument = new SpecificInstrument();
}
catch {
    instrument = new BaseInstrument();
}

【讨论】:

  • 这绝对是我认为我缺少的简单答案,谢谢!最后,我最终用一个通用工厂类抽象了这个检查,该类在给定情况下产生正确类型的实例,但我相信这是正确答案的最基本形式。
猜你喜欢
  • 2011-11-13
  • 2021-05-24
  • 2011-09-27
  • 2016-07-19
  • 2018-07-21
  • 1970-01-01
  • 2015-08-18
  • 2018-07-16
  • 2013-04-05
相关资源
最近更新 更多