对于多个选择支的应用,简单的我们多用If解决,或者应用Switch来做。对于比较复杂的应用,用Switch处理难维护,难扩展。
为了解决这个问题,我们通常可以用设计模式【比如策略模式】来解决。下面的这个解决方式来自CodeProject一个Programmer的解决方案,也可以轻松解决。

Code
using System;
using System.Collections.Generic;
namespace ResharperDemo
{
class Program
{
delegate bool Preperation();
static void Main(string[] args)
{
Program p=new Program();
p.ShowInfo();
}
private void UseSwitchMethod(Food food)
{
switch (food)
{
case Food.Apple:
{
PeelApple();
}
break;
case Food.AppleJuice:
{
BakePie();
}
break;
default:
break;
}
}
private void ShowInfo()
{
Dictionary<Food, Preperation> foodPreperation = new Dictionary<Food, Preperation>();
foodPreperation.Add(Food.Apple, PeelApple);
foodPreperation.Add(Food.ApplePie, BakePie);
foodPreperation.Add(Food.AppleJuice, MakeAppleJuice);
foodPreperation.Add(Food.Pizza, BakePizza);
Food food = Food.Apple;
foodPreperation[food]();
}
static bool PeelApple()
{
Console.WriteLine("Call PeelApple");
return true;
}
static bool BakePie()
{
Console.WriteLine("Call BakePie");
return true;
}
static bool MakeAppleJuice()
{
Console.WriteLine("Call MakeAppleJuice");
return true;
}
static bool BakePizza()
{
Console.WriteLine("Call BakePizza");
return true;
}
}
enum Food
{
Apple,
ApplePie,
AppleJuice,
Pizza
}
}