gpt4 book ai didi

c# - 动态开关盒

转载 作者:太空宇宙 更新时间:2023-11-03 17:17:01 25 4
gpt4 key购买 nike

我正在尝试为几个不同的用户制作一个简单的开关盒控制台菜单:adminmoderatoruseradmin 将具有 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;
}

主持人开关盒:

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;
}

有什么方法可以将这些开关盒组合成一个动态开关吗?如果我的想法或解释有误,请纠正我。

最佳答案

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]();

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

为了实现“默认”逻辑,你会使用类似的东西:

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
}

关于c# - 动态开关盒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33107026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com