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); } } } }
    };
}
相关推荐
mxwin6 小时前
Unity Shader 光线追踪原理与实战案例
unity·游戏引擎
samble11 小时前
从零搭建灌装监控系统(十九):单元测试实战,xUnit + 内存SQLite + 反射测试私有方法
c#·wpf·mvvm·modbus·工业控制
人道领域13 小时前
【面试八股速通篇01】锁与并发工具
java·开发语言·面试·c#
宇卿.14 小时前
C#字段、属性、索引器、常量
开发语言·计算机视觉·c#
程序员Linc14 小时前
ONNXOCRSharp 开源手记 02|v0.4.0 PDF识别
开发语言·pdf·c#·ocr·onnxocrsharp
地狱为王14 小时前
Unity使用DPDFNet实现实时语音增强(降噪)
unity·语音增强·降噪·dpdfnet
慧都小妮子15 小时前
MSG 附件太占内存?Aspose.Email for .NET 26.9 延迟加载
c#·.net·aspose·内存优化·延迟加载·aspose.email·附件内存
慧都小妮子15 小时前
FastReport PDF/UA 导出:让出海 PDF 满足无障碍合规要求
pdf·c#·fastreport·报表导出·pdf/ua·pdf 无障碍
平行云PVT15 小时前
国产信创实时云渲染解决方案:如何实现数字孪生与三维应用云化部署?
unity·webrtc·unreal engine·实时云渲染·国产信创·摩尔线程·砺算科技
夏炎黄16 小时前
Terrain地形剪裁
unity