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); } } } }
    };
}
相关推荐
似水明俊德7 小时前
02-C#.Net-反射-面试题
开发语言·面试·职场和发展·c#·.net
阿蒙Amon9 小时前
C#常用类库-详解SerialPort
开发语言·c#
似水明俊德10 小时前
02-C#.Net-反射-学习笔记
开发语言·笔记·学习·c#·.net
mxwin11 小时前
Unity Shader FLOWMAP岩浆流动制作案例
unity·游戏引擎·shader·uv
小贺儿开发11 小时前
【Arduino与Unity交互探究】01 摇杆模块
科技·unity·游戏引擎·arduino·串口通信·摇杆·硬件交互
Yasin Chen13 小时前
Unity TMP_SDF 分析(三)顶点着色器1
unity·游戏引擎·着色器
mxwin14 小时前
Unity Shader 使用 Noise 图 制作Shader 溶解效果
unity·游戏引擎
.NET修仙日记16 小时前
Acme.ReturnOh:让.NET API返回值处理更优雅,统一响应格式一步到位
c#·.net·webapi
mxwin16 小时前
Unity Shader 用 Ramp 贴图实现薄膜干涉效果
unity·游戏引擎·贴图·shader·uv
魔士于安16 小时前
Unity星球资源,八大星球,带fps显示
游戏·unity·游戏引擎·贴图·模型