mardi 11 août 2020

Using reflection to get all classes that implement a interface and only initialise class that matches ID/opcode given

So in the following code, there is a Instruction interface that is used by a number of classes such as AddInstruction, DivideInstruction and so on. Each of the classes that implements the interface assignes a label and opcode as per the Instruction interface.

Instruction.cs

public abstract class Instruction
    {
        private string label;
        private string opcode;

        protected Instruction(string label, string opcode)
        {
            this.label = label;
            this.opcode = opcode;
        }

        public abstract void Execute(Machine m);
    }

Example of one of the many instructions all of which have the same basic functionalities

AddInstruction.cs

public class AddInstruction : Instruction
    {
        
        private int reg, s1, s2;

        public AddInstruction(string lab, int reg, int s1, int s2) : base(lab, "add") // here the base interface is Instruction and we are assigning the opcode as add, other instructions have there own opcodes //
        {
            this.reg = reg;
            this.s1 = s1;
            this.s2 = s2;
        }

        public override void Execute(Machine m) =>
            // do something
}

From here I want to use the factory pattern along with Reflection to make it so in the future new instructions with there own opcodes can be initiated based on the opcode provided.

InstructionFactoryInterface.cs

interface InstructionFactoryInterface
    {
        Instruction GetInstruction(string opcode);
    }

InstructionFactory.cs

class InstructionFactory : InstructionFactoryInterface
    {
        public Instruction GetInstruction(string opcode)
        {
            Type type = typeof(Instruction);
            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsAssignableFrom(p));
            foreach (var type1 in types)
            {
                // loop through all the types and only return the class that has a matching opcode //
            }
   }

Now here is where i am suck, how can i loop through all the types that implement the Instruction interface and only return the type that matches the opcode parameter passed in. Thank you





Aucun commentaire:

Enregistrer un commentaire