C#反射问题:如何调用参数可变的方法??

ciduoyouyunan 2009-04-27 04:58:35
一个Test类

class Test
{
public void Write(string s)
{
Console.WriteLine("你输入的是:" + s);
}
public void Write(string s, int i)
{
Console.WriteLine("你输入的是:" + s);
Console.WriteLine("你输入的数字是:" +i);
}
}

我想通过反射来调用Write(string s, int i)方法.请问如何办到....
...全文
224 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wartim 2009-04-27
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ConsoleApplication16
{
class Program
{
static public void Write(string s)
{
Console.WriteLine("你输入的是:" + s);
}
static public void Write(string s, int i)
{
Console.WriteLine("你输入的是:" + s);
Console.WriteLine("你输入的数字是:" + i);
}

static void Main(string[] args)
{
Assembly Ass = Assembly.GetExecutingAssembly();
Type AssType = Ass.GetType("ConsoleApplication16.Program");
Object Obj = Activator.CreateInstance(AssType);
MethodInfo MI = AssType.GetMethod("Write", new Type[] { typeof(String) });
MI.Invoke(Obj, new Object[] { "A" });
MI = AssType.GetMethod("Write", new Type[] { typeof(String), typeof(int) });
MI.Invoke(Obj, new Object[] { "A", 1 });
Console.Read();
}
}
}
zgke 2009-04-27
  • 打赏
  • 举报
回复
Test _Info =new Test();
Type _TypeInfo = _Info.GetType();

MethodInfo _Method= _TypeInfo.GetMethod("Write",new Type[]{typeof(string),typeof(int)});
_Method.Invoke(_Info, new object[] {"AAA",1 });



调用 Write(string s)

MethodInfo _Method = _TypeInfo.GetMethod("Write", new Type[] { typeof(string) });
_Method.Invoke(_Info, new object[] { "AAA"});
gomoku 2009-04-27
  • 打赏
  • 举报
回复
GetMethod不是还有另外一个重载,允许你指定参数类型?

Type.GetMethod(string name, Type[] types);

111,126

社区成员

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

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

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