关联两组值
本文关键字:两组 关联 | 更新日期: 2023-09-27 18:37:11
我有以下代码 -
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/字符串对的列表将显着增加。 上面代码中的那些只是我打算使用的前三个。
可以使用枚举:
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);
您可以方便地使用枚举来传递值,并且仅在处理外部接口时将它们转换为整数或字符串。
这里有简单的字典,应该适合您的需求:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("All", 0);
dictionary.Add("Office", 50);
dictionary.Add("Manager", 100);
打印所有键/值对:
foreach (KeyValuePair<string, int> keyValuePair in dictionary)
{
Console.WriteLine("Key: "+keyValuePair.Key+", Value: "+keyValuePair.Value);
}
或者使用像 Szymon 这样的枚举。