mercredi 12 février 2020

Prompt user for values for all public properties on a class

C# makes it relatively easy to get all public properties , or get a property value by name.

But what about setting property values? For a simple test application I would like to be able to do something like this pseudocode which enumerates public properties on a class instance, prompts the user for values, and sets the properties based on these values - converting from input strings to property types as needed:

for(Property p in typeof(instance))
{
 s = ReadLine("Enter the value for {p.Name}, type {p.Type}");
 SetPropertyValue(instance,p.Name, p.Type.parse(s));
}

The major issue I come across that makes a general utility method SetPropertyValue difficult is that Parse doesn't always exist. It does on most basic types but not for string of course or for higher-level types.

I don't mind if it fails on types it doesn't support because my use would basically be int,short,string, byte, etc but how can I employ reflection to knock something up for console mode test apps?





Aucun commentaire:

Enregistrer un commentaire