簡體   English   中英

基於構造函數異常將派生類實現為基礎?

[英]Implement Derived Class as Base on Constructor Exception?

我正在使用代碼來實現硬件測試系統,該系統涉及與多個台式儀器的通信。 當我實例化這些工具之一的實例時,構造函數嘗試打開與該工具的通信會話。 如果失敗了,我會拋出各種錯誤,但是我想做的是使Instrument對象默認為虛擬或仿真模式,在該模式下不進行任何實際通信,但我仍然可以運行我的代碼。

現在,我擁有從基類繼承的一種類型的所有樂器。 我已將虛擬方法添加到執行這些調試功能的基類中,但是我仍然堅持一種干凈的方法,即在創建時修改派生對象,以在通信會話失敗時實現基類方法。

理想的解決方案是讓構造函數(從技術上講是new關鍵字)返回基類的實例而不是派生類,但是我已經做了很多搜索,但似乎不可能。

我可以在派生類中添加一個屬性,以用作布爾標志,派生類中的每個方法都會對該標志進行測試,如果為true,則調用基類方法,但是我希望找到一種更優雅的解決方案需要幾百條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
    }
}

我覺得我可能缺少解決這個問題的明顯方法,但是我已經花了好幾個小時摸索了。

您不能從SpecificInstrument構造函數返回BaseInstrument

一種選擇是將這種邏輯放在創建該工具的位置:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM