我有以下代码-
public static int GetViewLevel(string viewLevelDesc)
{
try
{
switch (viewLevelDesc)
{
case "All":
return 0;
case "Office":
return 10;
case "Manager":
return 50;
default:
throw new Exception("Invalid View Level Description");
}
}
catch (Exception eX)
{
throw new Exception("Action: GetViewLevel()" + Environment.NewLine + eX.Message);
}
}
public static string GetViewLevelDescription(int viewLevel)
{
try
{
switch (viewLevel)
{
case 0:
return "All";
case 10:
return "Office";
case 50:
return "Manager";
default:
throw new Exception("Invalid View Level Description");
}
}
catch (Exception eX)
{
throw new Exception("Action: GetViewLevelDescription()" + Environment.NewLine + eX.Message);
}
}
这两个静态方法使我能够从字符串 ViewLevelDesc 中获取一个 int ViewLevel,反之亦然。我确信我这样做的方式比它需要的要麻烦得多,我正在寻找一些建议如何实现相同的目标但更简洁。 int/string 对的列表将显着增加。上面代码中的只是我打算使用的前三个。
最佳答案
您可以使用枚举:
public enum Level
{
All = 0,
Office = 50,
Manager = 100
}
您可以通过这种方式从枚举中获取整数和字符串值:
Level level = Level.Manager;
int intLevel = (int)level;
string strLevel = level.ToString();
反之亦然
Level l1 = (Level)intLevel;
Level l2 = (Level)Enum.Parse(typeof(Level), strLevel);
您可以方便地使用枚举来传递值,并且在处理外部接口(interface)时只将它们转换为整数或字符串。
关于c# - 关联两组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19654608/