Difference between revisions of "2021 - Reflection"
(Created page with "=The Code= The code below is from the HexGrid class, and it is a section of the ExecuteCommandInTile method: <syntaxhighlight lang=c#> Piece thePiece = tiles[tile...") |
|||
Line 27: | Line 27: | ||
=Explanation= | =Explanation= | ||
− | If you remember the LESSPiece class, and the PBDSPiece class contain methods for 'Saw' and 'Dig'. | + | 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 in use has the method specified by the command (ie items[0]). | ||
+ | |||
+ | Reflection is used to create an object of 'method', and will be assigned the 'Saw' or 'Dig' method (depending on the piece). | ||
+ | |||
+ | The 'method.Invoke' command will then execute the method. | ||
+ | |||
+ | =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. |
Revision as of 10:01, 24 September 2020
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 in use has the method specified by the command (ie items[0]).
Reflection is used to create an object of 'method', and will be assigned the 'Saw' or 'Dig' method (depending on the piece).
The 'method.Invoke' command will then execute the method.
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.