C#中怎么用字符串去执行相应的带参数的函数名?

jacobwc 2006-09-08 01:48:14
比如从TextBox1.Text=getname
而getname又是个函数名
可以通过反射解决
比如:using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;

namespace Kchen
{
public class Test
{
Test()
{
}
public string test1 ()
{
return "yumen";
}
public static void test2()
{
object ha = Activator.CreateInstance(typeof(Test), true);
Test he = ha as Test;
MethodInfo method = he.GetType().GetMethod("test1");
string hahei = (string)method.Invoke(he,null);
}
}
}

但是函数遇到带参数如何解决?
getname(int a)
...全文
435 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
pretty_soft 2006-09-09
  • 打赏
  • 举报
回复
invokmember的最后一个参数不就是参数吗?

直接用对象
object obj1 = Activator.CreateInstance(typeof(getbh), true);
string s1=obj1.gettype().invokmember("method",getmethod,obj1,null,new object[]{"dasd"});
改改哈
我没试
jacobwc 2006-09-09
  • 打赏
  • 举报
回复
object obj1 = Activator.CreateInstance(typeof(getbh), true);
getbh he1 = obj1 as getbh;
MethodInfo method = he1.GetType().GetMethod(name);
string opl=newTable.Rows[i][3].ToString().Trim();//所传递的参数
object[] par=new object[]{};
string t1 = (string)method.Invoke(he1,par);//new object[]{opl}
运行到最后一句
提示“其他信息: 未将对象引用设置到对象的实例。”
jacobwc 2006-09-08
  • 打赏
  • 举报
回复

其他信息: 未将对象引用设置到对象的实例。
jacobwc 2006-09-08
  • 打赏
  • 举报
回复
MethodBase.Invoke Method (Object, Object[]) [C#]
public object Invoke(
object obj,
object[] parameters
);

这干吗的?
qw_study 2006-09-08
  • 打赏
  • 举报
回复
snowmagic 2006-09-08
  • 打赏
  • 举报
回复
object ha = Activator.CreateInstance(typeof(Test), true);
Test he = ha as Test;
MethodInfo method = he.GetType().GetMethod("test1");
//string hahei = (string)method.Invoke(he,null);
int a = 0;
string hahei = (string)method.Invoke(he,new object[]{a});


MethodBase.Invoke Method (Object, Object[]) [C#]
public object Invoke(
object obj,
object[] parameters
);

110,502

社区成员

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

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

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