Solving the 'Virtual method call in constructor' issue

前端 未结 5 1739
悲哀的现实
悲哀的现实 2020-12-31 03:22

I am making a software in c#. I am using an abstract class, Instruction, that has these bits of code:

protected Instruction(InstructionSet instr         


        
5条回答
  •  耶瑟儿~
    2020-12-31 03:51

    You could pass in the real instruction into the base class constructor:

    protected Instruction(..., Instruction realInstruction)
    {
        //Some stuff
    
        if (DoesUseRealInstruction) {
            RealInstruction = realInstruction;
        }
    }
    
    public DerivedInstruction(...)
        : base(..., GetRealInstruction(...))
    {
    }
    

    Or, if you really want to call a virtual function from your constructor (which I highly discorage you from) you could suppress the ReSharper warning:

    // ReSharper disable DoNotCallOverridableMethodsInConstructor
        RealInstruction = GetRealInstruction(instructionSet, Argument);
    // ReSharper restore DoNotCallOverridableMethodsInConstructor
    

提交回复
热议问题