关于使用枚举作为索引的优化
看了别人的博客学的,记录下,留用!
源代码
enum TemplateCode
{
None = 0,
Head = 1,
Menu = 2,
Foot = 3,
Welcome = 4,
}
public string GetHtml(TemplateCode tc)
{
switch (tc)
{
case TemplateCode.Head:
return GetHead();
case TemplateCode.Menu:
return GetMenu();
case TemplateCode.Foot:
return GetFoot();
case TemplateCode.Welcome:
return GetWelcome();
default:
throw new ArgumentOutOfRangeException("tc");
}
}
优化后
public enum TemplateCode
{
Head = 1,
Menu = 2,
Foot = 3,
Welcome = 4
}
public string GetHtml(TemplateCode tc, string msg)
{
Func<string, string> func;
if (TemplateDict.TryGetValue(tc, out func))
{
return func(msg);
}
return "do nothing";
}
public readonly static Dictionary<TemplateCode, Func<string, string>> TemplateDict = InitTemplateFunction();
private static Dictionary<TemplateCode, Func<string, string>> InitTemplateFunction()
{
var ditc = new Dictionary<TemplateCode, Func<string, string>>();
ditc.Add(TemplateCode.Head, GetHead);
ditc.Add(TemplateCode.Menu, GetMenu);
ditc.Add(TemplateCode.Foot, GetFoot);
ditc.Add(TemplateCode.Welcome, GetWelcome);
return ditc;
}
public static string GetHead(string msg)
{
return msg + "a";
}
public static string GetMenu(string msg)
{
return msg + "b";
}
public static string GetFoot(string msg)
{
return msg + "c";
}
public static string GetWelcome(string msg)
{
return msg + "d";
}