2021 - Reflection

From TRCCompSci - AQA Computer Science
Revision as of 10:05, 24 September 2020 by Admin (talk | contribs) (Explanation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The Code

The code below is from the HexGrid class, and it is a section of the ExecuteCommandInTile method:

            Piece thePiece = tiles[tileToUse].GetPieceInTile();
            items[0] = items[0][0].ToString().ToUpper() + items[0].Substring(1);
            if (thePiece.HasMethod(items[0]))
            {
                string methodToCall = items[0];
                Type t = thePiece.GetType();
                System.Reflection.MethodInfo method = t.GetMethod(methodToCall);
                object[] parameters = { tiles[tileToUse].GetTerrain() };
                if (items[0] == "Saw")
                {
                    lumber += Convert.ToInt32(method.Invoke(thePiece, parameters));
                }
                else if (items[0] == "Dig")
                {
                    fuel += Convert.ToInt32(method.Invoke(thePiece, parameters));
                    if (Math.Abs(fuel) > 2)
                    {
                        tiles[tileToUse].SetTerrain(" ");
                    }
                }
             }

Explanation

If you remember the LESSPiece class, and the PBDSPiece class contain methods for 'Saw' and 'Dig'.

The main if statement will check to see if the piece object in use has the method specified by the command (ie items[0] which will be 'Saw' or 'Dig').

Reflection is used to create an object of 'method', and will be assigned the 'Saw' or 'Dig' method from the object (depending on the piece).

The 'method.Invoke' command will then execute the method within the object.

Issues

This is an advanced programming technique and is not covered by the specification. It would therefore be unlikely to be the basis of a question.