动态开关案例

Rim*_*nas 1 c# switch-statement

我试图做一个简单的开关情况下控制台菜单中的几个不同的用户:admin,moderator,和user.admin将有create, delete, modify, show功能,moderator- create, modify, show功能和user- create, show功能可供选择.

管理员开关案例:

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;
}
Run Code Online (Sandbox Code Playgroud)

主持人开关案例:

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;
}
Run Code Online (Sandbox Code Playgroud)

用户开关案例:

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;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将这些开关盒塑造成一个动态开关?如果我在思考或解释错误,请纠正我.

Ben*_*igt 7

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

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]();
Run Code Online (Sandbox Code Playgroud)

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

为了实现"默认"逻辑,你可以使用类似的东西:

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
}
Run Code Online (Sandbox Code Playgroud)