【发布时间】:2010-05-19 10:34:24
【问题描述】:
如何重构该代码?
public enum enum1
{
value1 = 0x01,
value2 = 0x02,
value3 = 0x03,
value4 = 0x04,
value5 = 0x05,
UNKNOWN = 0xFF
}
class class1
{
private const string STR_VALUE1 = "some text description of value1";
private const string STR_VALUE2 = "some text description of value2";
private const string STR_VALUE3 = "some text description of value3";
private const string STR_VALUE4 = "some text description of value4";
private const string STR_VALUE5 = "some text description of value5";
private const string STR_VALUE6 = "some text description of unknown type";
public static string GetStringByTypeCode(enum1 type)
{
switch(type)
{
case enum1.value1:
return STR_VALUE1;
case enum1.value2:
return STR_VALUE2;
case enum1.value3:
return STR_VALUE3;
case enum1.value4:
return STR_VALUE4;
case enum1.value5:
return STR_VALUE5;
default:
return STR_VALUE6;
}
}
}
PS:有很多 enum1...enumX 和 GetStringByTypeCode(enum1) ... GetStringByTypeCode(enumX) 方法。
编辑:我是这样重构的:
namespace ConsoleApplication4
{
public enum enum1
{
value1 = 0x01,
value2 = 0x02,
value3 = 0x03,
value4 = 0x04,
value5 = 0x05,
UNKNOWN = 0xFF
}
class class1
{
static Dictionary<enum1, string> _dict;
static class1()
{
_dict = new Dictionary<enum1, string>();
_dict.Add(enum1.value1, "some text description of value1");
_dict.Add(enum1.value2, "some text description of value2");
_dict.Add(enum1.value3, "some text description of value3");
_dict.Add(enum1.value4, "some text description of value4");
_dict.Add(enum1.value5, "some text description of value5");
_dict.Add(enum1.UNKNOWN, "some text description of unknown type");
}
public static string GetStringByTypeCode(enum1 type)
{
string result = string.Empty;
try
{
_dict.TryGetValue(type, out result);
}
catch
{
}
return result;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(class1.GetStringByTypeCode(enum1.value4));
Console.ReadKey();
}
}
}
【问题讨论】:
-
你想达到什么目的?代码少?能够更轻松地添加额外的价值/描述对吗?还有什么?
-
@Daniel,我认为该代码并不理想。也许有人可以提出一个更好的解决方案,所以我问一个问题......能够更轻松地添加额外的价值/描述对 --> 是的。
标签: c# refactoring