switch和硬编码字典的等效性

背景

写背包系统时点击物品格子,出现详情页,详情页的选项按钮根据物品种类、所属容器动态生成。这里生成选项按钮取决于的"键"有多个:物品种类、所属容器,执行的操作是生成几个按钮,写入名称、添加回调。按常规思路会写成2层判断,一个长度恐怖的函数。

改进

经过豆包的启发:

  1. 双键可以使用Tuple<>;
  2. switch可以用硬编码字典;
  3. case后面的操作可以用委托存放;

变成了这样一个硬编码字典:虽然还是很长,但是比原来的写法(200多行)已经好多了,而且更整齐了。

cs 复制代码
public class ButtonConfig
{
    public string hint;
    public UnityAction callback;
}
Dictionary<(CellLocation, Props_Type), List<ButtonConfig>> buttonConfigs;
void InitOptionConfigs()
{
    buttonConfigs = new() {
        //场景内物品选项
        {(CellLocation.Scene,Props_Type.Gun),
            new(){ new ButtonConfig { hint="拾取",callback=()=>{ TakeGunFromGround(cellSelected);} } } },
        {(CellLocation.Scene, Props_Type.Mag),
            new(){ new ButtonConfig { hint="拾取",callback=()=>{ PickMagFromScene(cellSelected);} } }},
        {(CellLocation.Scene, Props_Type.Medicine),
            new(){ new ButtonConfig { hint="拾取",callback=()=>{ PickFromScene(cellSelected);} } }},
        {(CellLocation.Scene, Props_Type.Grenade),
            new(){ new ButtonConfig { hint="拾取",callback=()=>{ PickFromScene(cellSelected);} } }},
        //玩家背包内物品选项
        {(CellLocation.PlayerPack, Props_Type.Mag),
        new (){new ButtonConfig {hint="放下",callback=()=> { if (putIn){PutMagInCrate(cellSelected);
            }else{DropMag(cellSelected);} } } }},
        {(CellLocation.PlayerPack, Props_Type.Medicine),
        new (){new ButtonConfig {hint="放下",callback=PutItem},
            new ButtonConfig{hint="使用",callback=TryUseMedicine} } },
        {(CellLocation.PlayerPack, Props_Type.Grenade),
        new(){ new ButtonConfig {hint="放下",callback= PutItem },
        new ButtonConfig{hint="使用",callback=TryUseGrenade } } },
        //其他容器内物品选项
        {(CellLocation.OtherPack, Props_Type.Mag),
        new(){ new ButtonConfig {hint="拾取",callback=()=>{PickMagFromCrate(cellSelected);} }}},
        {(CellLocation.OtherPack, Props_Type.Medicine),
        new(){new ButtonConfig {hint="拾取",callback=()=>{PickFromCrate(cellSelected);} } } },
        {(CellLocation.OtherPack, Props_Type.Grenade),
        new(){new ButtonConfig {hint="拾取",callback=()=>{PickFromCrate(cellSelected);} } } },
        {(CellLocation.OtherPack, Props_Type.Gun),
        new(){ new ButtonConfig {hint="拾取",callback=()=> { TakeGunFromCrate(cellSelected); } } } }
    };
}
相关推荐
xiaoshuaishuai87 小时前
C# 签名异常与Gas预估失败调试方案
开发语言·网络·tcp/ip·c#
xiaoshuaishuai87 小时前
C# Gemini 辅助网络安全漏洞分析
开发语言·web安全·c#
风继续吹..7 小时前
C# 文件输入输出 精简理解
开发语言·c#
魔法阵维护师8 小时前
从零开发游戏需要学习的c#模块,第十章(设计模式入门)
学习·游戏·设计模式·c#
风继续吹..8 小时前
C# 文件 IO 实操练习题 5道
开发语言·c#
苦荞米8 小时前
C#中,Ticks不能作为时间戳使用。
c#
吴可可1239 小时前
Teigha处理CAD样条曲线的方法解析
数据库·算法·c#
XS0301069 小时前
并发编程三
开发语言·c#
魔法阵维护师13 小时前
从零开发游戏需要学习的c#模块,第二十章(2D 敌人与战斗触发)
学习·游戏·c#
我是唐青枫14 小时前
C#.NET YARP + OpenTelemetry:网关链路追踪实战
开发语言·c#·.net