C#,按名称启动功能 [英] C#, starting function by name

查看:79
本文介绍了C#,按名称启动功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Guys,



需要一些建议。



我在数据库中有一个字符串:

PerformInjection {param} DataDict {param} ObjectArray



现在 - 我解析这个字符串并将其拆分为数组:

Hello Guys,

Need some advice.

I got a string in the database:
"PerformInjection{param}DataDict{param}ObjectArray"

Now - I parse this string and split it into array:

[0] = "PerformInection"
[1] = "DataDict"
[2] = "ObjectArray"





现在我需要做的就是运行函数,其名称在[0]中,并将其他字符串数组元素作为参数传递给它。最后 - 这样的代码应该执行:





Now what I need to do is to run the function, which name is in [0] and pass other string array elements as parameters to it. So finaly - such code should get executed:

PerformInjection(DataDict, ObjectArray);





有关如何以最优雅的方式实现这一目标的任何想法? (请注意,在这个例子中,我只有2个参数应该传递给函数。可能是我将有3,4,5等参数传递。所以规则很简单 - string [0]总是函数名称和其他所有 - 参数)。



顺便说一下 - 我已经完成了解析参数值,所以只需找出最好的方法如何获得按名称运行并传递我得到的那些参数。考虑代表,但不确定这是否是最好的方法。



谢谢!



Any thought on how to achieve this in the most graceful manner? (Please note that in this example I got only 2 parameters that should be passed to function. It might be that I will have 3,4,5 and so on parameters to pass. So the rule is simple - string[0] is always function name and everything else - parameters).

By the way - I've done resolving parameter values, so only need to find out the best approach how to get the function by name and pass those parameters that I got. Was thinking about delegates, but not sure if it's the best approach.

Thanks!

推荐答案

使用反射 - 动态调用方法,给定方法名称和类的字符串名称 [ ^ ]。



这是另一个简单的例子 - C#GetMethod [ ^ ]。
Use reflection - Dynamically Invoke A Method, Given Strings with Method Name and Class Name[^].

Here is another simple example - C# GetMethod[^].

这篇关于C#,按名称启动功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆