=?Utf-8?B?cm9kY2hhcg==?= said:
this validation routine is to my console application's menu option. i was
just wondering if they are other ways to do this. because it smells a little
like what if i put a new option in the menu but forget to add it to the array
(unlikely but just curious) is this something to worry about?
It's mostly a style option. I prefer to do something like this to
make the code a little more self documenting, and so new functions
don't need to modify existing functions to be implemented.
class Command : Attribute
{
public string Value;
public string Desc;
public Command(string Value, string Desc)
{
this.Value = Value;
this.Desc = Desc;
}
}
class Program
{
[Command("1", "This is option 1")]
static void Option1()
{
Console.WriteLine("You entered option 1");
}
[Command("2", "This is option 2")]
static void Option2()
{
Console.WriteLine("You entered option 2");
}
[Command("3", "This is option 3")]
static void Option3()
{
Console.WriteLine("You entered option 3");
}
[Command("4", "This is option 4")]
static void Option4()
{
Console.WriteLine("You entered option 4");
}
[Command("E", "Exit")]
static bool OptionE()
{
Console.WriteLine("You entered option E");
return false;
}
[Command("?", "Show help")]
static void ShowHelp()
{
foreach (MethodInfo mi in typeof(Program).GetMethods(
BindingFlags.Static | BindingFlags.NonPublic))
{
foreach (object cur in mi.GetCustomAttributes(false))
{
if (cur is Command)
{
Console.Write(((Command)cur).Value);
Console.Write(" - ");
Console.WriteLine(((Command)cur).Desc);
break;
}
}
}
}
static void Main(string[] args)
{
bool readInput = true;
while (readInput)
{
Console.Write("] ");
string input = Console.ReadLine();
bool found = false;
foreach (MethodInfo mi in typeof(Program).GetMethods(
BindingFlags.Static | BindingFlags.NonPublic))
{
foreach (object cur in mi.GetCustomAttributes(false))
{
if (cur is Command && string.Compare(
((Command)cur).Value, input, true) == 0)
{
object ret = mi.Invoke(null, null);
if (ret is bool && ((bool)ret) == false)
{
readInput = false;
}
found = true;
break;
}
}
if (found)
{
break;
}
}
if (!found)
{
Console.WriteLine("Unknown command");
}
}
}
}