Solving the 'Virtual method call in constructor' issue

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

    You can introduce another abstract class RealInstructionBase so your code will look like:

    public abstract class Instruction {
       public Instruction() {
           // do common stuff
       }
    }
    
    public abstract class RealInstructionBase : Instruction {
       public RealInstructionBase() : base() {
           GetRealInstruction();
       }
    
       protected abstract object GetRealInstruction();
    }
    

    Now each instruction which needs to use RealInstruction derives from RealInstructionBase and all others derive from Instruction. This way you should have them all correctly initialized.

    EDIT: Ok, this will only give you a cleaner design (no if in constructor) but does not get rid of the warning. Now if you would like to know why you get the warning in the first place, you can refer to this question. Basically the point is that you will be safe when you mark your classes where you are implementing the abstract method as sealed.

提交回复
热议问题