小编sna*_*ard的帖子

如何在 C# 中使用基于运行时动态类型的泛型调度替换枚举上的 switch 语句?

背景

我正在为 Unity 构建一个编辑器扩展(尽管这个问题与 Unity 并不严格相关)。用户可以从下拉列表中选择二元运算,并对输入执行该运算,如图所示:

用户选择的二元运算

该代码取自教程,并在此处结合使用枚举switch语句来实现所需的行为。

下一张图演示了图形 UI 中代码和行为之间的关系:

在此输入图像描述

问题

根据我之前用其他语言编程的经验,以及我希望允许用户可扩展的操作,而不需要用户在核心代码中编辑 switch 语句,我希望生成的代码看起来像这样(无效) C#代码:

... snip ...

        // OperatorSelection.GetSelections() is automagically populated by inheritors of the GenericOperation class
        // So it would represent a collection of types?
        // so the confusion is primarily around what type this should be
        public GenericOperations /* ?? */ MathOperations = GenericOperation.GetOperations();

        // this gets assigned by the editor when the user clicks 
        // the dropdown, but I'm unclear on …
Run Code Online (Sandbox Code Playgroud)

c# generics metaprogramming unity-game-engine dispatch

7
推荐指数
1
解决办法
711
查看次数