c#动态执行本类中的方法

stevenzhao1 2016-06-02 03:45:04
如题

string fun =context.Request.Form.Get("fun");// 方法
string args=context.Request.Form.Get("args");// 参数
exec(fun,args);// 这一句应该怎么调用?
...全文
219 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xdashewan 2016-06-02
  • 打赏
  • 举报
回复
反射真心没必要,if else就足够的东西,非要搞成代码洁癖真心没必要。与其走反射,还不如定义个字典类,里面放Func或者action之类的泛型委托,直接用key去拿到委托去执行
stevenzhao1 2016-06-02
  • 打赏
  • 举报
回复
搞定了,如下代码 string fun =context.Request.Form.Get("fun");// 方法 object o = Activator.CreateInstance(this.GetType()); Type type = this.GetType(); object[] par = new object[] { };// 参数 // 调用方法 string str = (string)type.InvokeMember(fun.Trim(), BindingFlags.Default | BindingFlags.InvokeMethod, null, o, par);
  • 打赏
  • 举报
回复
用反射来调用

                    Type type = fs.GetType();  // fs是你包含有方法的类的实例
                    System.Reflection.MethodInfo funMethod = type.GetMethod("fun");   // 假设方法名是fun
                    funMethod.Invoke(fs, parameters);
// parameters是fun需要的参数
stevenzhao1 2016-06-02
  • 打赏
  • 举报
回复
方法是在同一个类中写好的,只不过要根据前端传递的参数来调用对应的方法。switch case判断就不用说了

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧