43 - Considera as seguintes enumerações:
enum Terrain
{
Rock = 0,
Plains,
Forest,
Jungle
}
enum BonusTerrain
{
Water = 1,
Food
}
Escreve dois métodos overloaded chamados Eat()
, um que aceite um Terrain
e devolva o valor numérico do respetivo membro da enumeração Terrain
, e outro
que aceite um BonusTerrain
e devolva o valor numérico do respetivo membro da
enumeração BonusTerrain
multiplicado por 10. Coloca os 2 métodos como
static
numa classe chamada Grazer
(namespace LP1Exercises
), e escreve
um método Main
para testar os métodos que criaste.
namespace LP1Exercises
{
class Grazer
{
// Returns index nº of a member of Terrain
public static int Eat(Terrain terrain)
{
// Converting member of enum to int
int y = (int)terrain;
return y;
}
// Returns index nº of a member of BonusTerrain *10
public static int Eat(BonusTerrain bonusTerrain)
{
// Converting member of enum to int
int y = (int)bonusTerrain;
// Returning y times 10
return y * 10;
}
}
}
using System;
namespace LP1Exercises
{
class Program
{
static void Main(string[] args)
{
// Testing methods from Grazer
// Calling Terrain enum
Console.WriteLine
($"Jungle Terrain: {Grazer.Eat(Terrain.Jungle)}");
Console.WriteLine
($"Forest Terrain: {Grazer.Eat(Terrain.Forest)}");
// Calling BonusTerrain enum
Console.WriteLine
($"Water, Bonus Terrain: {Grazer.Eat(BonusTerrain.Water)}");
Console.WriteLine
($"Food, Bonus Terrain: {Grazer.Eat(BonusTerrain.Food)}");
}
}
}
Por João Rebelo
namespace LP1Exercises
{
/// <summary>
/// Cointains methods for returning enum values
/// </summary>
class Grazer
{
/// <summary>
/// Method that returns the given Terrain value
/// </summary>
/// <param name="terrain">A terrain from Terrain enum</param>
/// <returns>
/// Returns an int value corresponding to Terrain enum
/// </returns>
public static int Eat(Terrain terrain) =>
(int) terrain;
/// <summary>
/// Method that returns the given BonusTerrain value * 10
/// </summary>
/// <param name="bonusTerrain">
/// A bonusTerrain from BonusTerrain enum
/// </param>
/// <returns>
/// Returns an int value corresponding to BonusTerrain enum * 10
/// </returns>
public static int Eat(BonusTerrain bonusTerrain) =>
(int) bonusTerrain * 10;
}
}
using System;
namespace LP1Exercises
{
/// <summary>
/// Testing Eat methods
/// </summary>
class Program
{
/// <summary>
/// Tests the overloaded methods Eat() and displays the return
/// </summary>
/// <param name="args">
/// Command line arguments that represent a String array
///</param>
static void Main(string[] args)
{
// Printing the Forest, Plains, Jungle and Rock values
Console.WriteLine("BIOMES:\n" +
"\tForest: {0}\n" +
"\tPlains: {1}\n" +
"\tJungle: {2}\n" +
"\tRock: {3}\n\n"
,Grazer.Eat(Terrain.Forest),
Grazer.Eat(Terrain.Plains),
Grazer.Eat(Terrain.Jungle),
Grazer.Eat(Terrain.Rock));
// Printing the Food and Water values * 10
Console.WriteLine("SUPPLIES:\n" +
"\tFood: {0}\n" +
"\tWater: {1}"
,Grazer.Eat(BonusTerrain.Food),
Grazer.Eat(BonusTerrain.Water));
}
}
}
Por Afonso Rosa