简体   繁体   中英

Initialize base class without copy constructor from derived class constructor

I need to derive from a class Tool , as I must decorate that class with another interface IToolWrapper . Unfortunately, the Tool class does not provide a copy constructor, which is why I think one cannot write the contructor of the DerivedTool like

public DerivedTool(String filename) : base(createToolFromFile(filename)) {
    //...
}

Although I was quite sure it wouldn't work I tried the following:

public sealed class DerivedTool : Tool, IToolWrapper {

    static bool createToolFromFile(ref Tool tool, String filename) {
        tool.Dispose();
        tool = null;
        try {
            tool = LoadFromFile(filename) as Tool;
        } catch ( Exception ) {
            return false;
        }
        return true;
    }

    public DerivedTool(String filename) : base() {
        Tool tool = (Tool)this;
        if ( !createToolBlockFromFile(ref tool, filename) ) throw new Exception("Tool could not be loaded!");
    }

}

In the debugger, I see that tool as I local variable to the constructor is modified as required (b/c the catch case isn't entered), but the base part of DerivedTool (ie the Tool ) is not affected. How can I achieve the desired behavior?

Use combination of a private variable and implicit/explicit operator as like below:

public sealed class DerivedTool : IToolWrapper {
    private Tool _tool;

    public DerivedTool(String filename) : base() {
        _tool = LoadFromFile(filename) as Tool;
    }

    public static implicit operator Tool(DerivedTool dt)
    {
        return dt._tool;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM