这是一个有些简化的例子(我改变了它以隐藏实际代码)。 我有一个由数据库驱动的应用程序和一个正在独立开发的小工具,旨在与应用程序配合使用。有一个表定义了一个枚举,但它可能随时间而发生变化。假设某个应用程序(医学?)需要精确跟踪人的性别。
按id从sex表中选择*;
id | mnemonic | description
0 | U | Unknown sex
1 | M | Male
2 | F | Female
3 | T | Trans-gender
我的 C# 枚举
:
public enum SexType
{
/// <summary>Unknown sex.</summary>
[Description("U")]
Unknown = 0,
/// <summary>Male sex.</summary>
[Description("M")]
Male = 1,
/// <summary>Female sex.</summary>
[Description("F")]
Female = 2
/// <summary>Trans-gender sex.</summary>
[Description("T")]
TransGender = 3,
}
在这里,我不应该假设ID是连续的序列;即使看起来是这样,这些枚举标志也不能组合。
一些逻辑在SQL中完成;一些逻辑在C#
代码中完成。例如,我可能会有一个函数:
// Here we get id for some record from the database.
public static void IsMaleOrFemale(int sexId)
{
if (!Enum.IsDefined(typeof(SexType), sexId))
{
string message = String.Format("There is no sex type with id {0}.",
sexId);
throw new ArgumentException(message, "sexId");
}
var sexType = (SexType) sexId;
return sexType == SexType.Male || sexType == SexType.Female;
}
只要表格和枚举定义不变,这个方法就可以很好地工作。但是表格可能会发生变化。我不能依赖于id列或mnemonic列维持它们的值。我认为最好的方法是编写一个单元测试来确保表格与我的枚举定义同步。我试图将值匹配到id,将描述属性匹配到mnemonic列。
那么,如何通过查看“enum SexType”以编程方式获取所有配对列表:
(0,“U”),(1,“M”),(2,“F”),(3,“T”)
?这个想法是紧密比较这个有序列表和
select id, mnemonic from sex order by is asc;
。