Solving the 'Virtual method call in constructor' issue

前端 未结 5 1742
悲哀的现实
悲哀的现实 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:56

    When you create an instance of your derived class, your call stack will look like this:

    GetRealInstruction()
    BaseContructor()
    DerivedConstructor()
    

    GetRealInstruction is overridden in the derived class, whose constructor has not finished running yet.

    I don't know how your other code looks, but you should first check if you really needed a member variable in this case. You have a method that returns the object you need. If you really do need it, make a property and call GetRealInstruction() in the getter.

    Also you can make GetRealInstruction abstract. That way you don't have to throw the exception and compiler will give you an error if you forget to override it in a derived class.

提交回复
热议问题