动态开关案例 [英] Dynamic switch cases

查看:34
本文介绍了动态开关案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为几个不同的用户制作一个简单的 switch case 控制台菜单:adminmoderatoruser.admin 将具有 create、delete、modify、show 函数,moderator - create、modify、show 函数,以及user - create, show 可供选择的函数.

I'm trying to make a simple switch case console menu for a few different users: admin, moderator, and user. admin would have create, delete, modify, show functions, moderator - create, modify, show functions, and user - create, show functions to choose from.

管理员切换案例:

if(userType == "admin")
{
    string i = Console.ReadLine();
    switch(i):
    case "create": Console.WriteLine("Created");
                   break;
    case "modify": Console.WriteLine("Modified");
                   break;
    case "delete":Console.WriteLine("Deleted");
                  break;
    case "show":Console.WriteLine("Showed");
                break;
    default: Console.WriteLine("Default");
             break;
}

版主切换案例:

if(userType == "moderator")
{
    string i = Console.ReadLine();
    switch(i):
    case "create": Console.WriteLine("Created");
                   break;
    case "modify": Console.WriteLine("Modified");
                   break;
    case "show": Console.WriteLine("Showed");
                 break;
    default: Console.WriteLine("Default");
             break;
}

用户切换案例:

if(userType == "user")
{
    string i = Console.ReadLine();
    switch(i):
    case "create": Console.WriteLine("Created");
                   break;
    case "show": Console.WriteLine("Showed");
                 break;
    default: Console.WriteLine("Default");
             break;
}

有什么办法可以将这些开关盒塑造成一个动态开关?如果我的想法或解释有误,请纠正我.

Is there any way to mold these switch cases into one dynamic switch? If I'm thinking or explaining something wrong, please correct me.

推荐答案

switch-case 的动态等效项是字典查找.例如:

The dynamic equivalent of a switch-case is a dictionary lookup. For example:

Dictionary<string, Action> userActions = {
        { "create", () => Console.WriteLine("created") },
        { "show", () => Console.WriteLine("showed") } };
Dictionary<string, Action> adminActions = {
        { "create", () => Console.WriteLine("created") },
        { "show", () => Console.WriteLine("showed") },
        { "delete", () => Console.WriteLine("deleted") } };

Dictionary<string, Dictionary<string, Action>> roleCapabilities = {
        { "user", userActions },
        { "administrator", adminActions } };

roleCapabilities[userType][action]();

在运行时,您可以轻松地为每个角色(组)添加和删除允许的操作.

At runtime, you can easily add and remove allowed actions to each role (group).

为了实现默认"逻辑,您可以使用以下内容:

In order to implement "default" logic, you'd use something like:

Action actionCall;
if (roleCapabilities[userType].TryGetValue(action, out actionCall)) {
   actionCall();
}
else {
   // this is the "default" block, the specified action isn't valid for that role
}

这篇关于动态开关案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆