samedi 31 octobre 2020

Casting user input to enum (reflection)?

Let's say i have this class:

class Person
{
   public string Name { get; set; }
   public HairColour hairColour { get; set; }
   public EyeColour eyeColour { get; set; }
}

where HairColour and EyeColour are enums.

And I want the user to enter a value for each of the person's properties like this:

string userInput = "";

Person p = new Person();

Type personType = typeof(Person);

foreach (var property in personType.GetProperties())
{
   Console.Write("Enter the person's " + property.Name + ": ")
   userInput = Console.ReadLine();
   personType.GetProperty(property.Name).SetValue(p, // PARSE PROPERTY HERE );
}

Is there a way to cast the userInput to the corresponding type, without using multiple "if" statements?





Aucun commentaire:

Enregistrer un commentaire