小编Fir*_*tGI的帖子

给定类型变量动态调用方法

我的目标: 我有一个系统,我希望其他人能够添加一个包含特定方法的 C# 脚本,我可以在运行时从另一个类中查找和执行该方法。

我的方法: 我创建了一个带有方法的接口,因此我可以遍历任何使用反射实现该接口的类并列出它们,然后使所有这些类之间的方法名称相同。

我有一个类,它包含在查找过程中找到的所有类的枚举,用户可以在运行时在它们之间进行选择。

我现在需要能够获取所选类类型的方法并调用它的方法,问题是我肯定知道方法的名称,但类的类型存储为变量。

编码:

//来自内存的伪代码:

            //Possible solution 1:
            Type selectedType = typeSelectedByEnum;
            MethodInfo genericMethod = selectedType.GetMethod("TheInterfaceMethod").MakeGenericMethod(selectedType);
            genericMethod.Invoke(selectedType, new object[0]);

            //Possible solution 2: (however I would much prefer to use something avaliable prior to .NET 4.6)
            Type selectedType = typeSelectedByEnum;
            dynamic changedObj = Convert.ChangeType(selectedType, selectedType);//-Something here needs to implement IConvertable, how would I set this up?
            changedObj.TheInterfaceMethod();

            //Possible solution 3:

            //Your solution??!
Run Code Online (Sandbox Code Playgroud)

感谢任何帮助,在这一点上,我已经尝试了很多东西,并且对任何可能的运行时替代方案持开放态度。如有必要,我可以提供更多代码。

.net c# unity-game-engine

5
推荐指数
1
解决办法
673
查看次数

标签 统计

.net ×1

c# ×1

unity-game-engine ×1