这是一个稍微简化的示例(我对其进行了更改以隐藏实际代码)。
我有一个数据库驱动的应用程序和一个单独开发的小工具,旨在与该应用程序一起使用。有一个表定义了枚举,但它可能会随着时间的推移而改变。假设某个应用程序(医疗?)需要相当精确地跟踪一个人的性别。
select * from sex order by id;
id | mnemonic | description
0 | U | Unknown sex
1 | M | Male
2 | F | Female
3 | T | Trans-gender
And my C# enum
:
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 列或助记符列来维护它们的值。我认为我能做的最好的事情就是进行单元测试,以确保该表与我对枚举的定义同步。我试图将值与 id 相匹配,将描述属性与助记符列相匹配。
那么,如何获取所有对的列表(以编程方式,在C#
): (0, "U"), (1, "M"), (2, "F"), (3, "T")
通过查看enum SexType
?
这个想法是将这个有序列表与select id, mnemonic from sex order by is asc;
.