c# - 关联两组值

标签 c#

我有以下代码-

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/

相关文章:

c# - 混合 32 位和 64 位 P/Invoke

c# - WCF 403 错误

c# - 单击按钮时禁用选中的复选框

c# - 在 Entity Framework 中调用存储过程时的字符串准备

c# - 单击父窗口时子窗体不闪烁

c# - WPF:如何在 Windows 之间共享 httpClient

C# LINQ 选择直到数量 >= 0

c# - 如何异步启动线程?

c# - 激活 Windows 应用商店应用程序...失败,错误为 'The app didn' t start'

c# - Add-Migration 不会检测外键的更改