C# 反射 如何调用重载方法?

tommir3 2010-01-20 11:29:39
DLL中的类

public class Sample1
{
private string _str1 = "我是属性1";

public string Str1
{
get { return _str1; }
}

/// <summary>
/// 显示
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public string Display()
{
return "无参数方法";
}

/// <summary>
/// 显示
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public string Display(string s)
{
return s + "————有参方法";
}
}


我现在要调用Display(),但总是错,我想反射后调用时编译器不知道我要调哪个方法。

string path = System.IO.Directory.GetCurrentDirectory() + "\\lassLibrary1Demo.dll"; //获得当前项目所在的据对路径
Assembly ass = Assembly.LoadFile(path); //获取DLL的集合

Type tp = ass.GetType("lassLibrary1Demo.Sample1"); //获得DLL中的指定类型
object tmpobj = ass.CreateInstance("lassLibrary1Demo.Sample1");
MethodInfo mi = tp.GetMethod("Display"); //取的方法描述
string result = (string)mi.Invoke(tmpobj, null);
Console.Read();


现在的问题是报错,如何调用重载的方法呢?
...全文
1295 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
piao_31 2010-06-03
  • 打赏
  • 举报
回复
我也看看
W3286879 2010-03-12
  • 打赏
  • 举报
回复
我看看
tommir3 2010-01-20
  • 打赏
  • 举报
回复
谢谢,问题解决,
结贴。
tommir3 2010-01-20
  • 打赏
  • 举报
回复
谢谢,没有试,我先去吃饭了。。。
阿非 2010-01-20
  • 打赏
  • 举报
回复
MethodInfo mi = structType.GetMethod("Display",new Type[]{}); //取的方法描述
string result = (string)mi.Invoke(structInstance, null);
Console.WriteLine(result);
mi = structType.GetMethod("Display", new Type[] { typeof(String)}); //取的方法描述
result = (string)mi.Invoke(structInstance, new object[] { "a"});
Console.WriteLine(result);
ouc_ajax 2010-01-20
  • 打赏
  • 举报
回复
MethodInfo mi = tp.GetMethod("Display", new Type[] { typeof(string)});

重载的方法可以通过参数区分

public MethodInfo GetMethod(
string name,
Type[] types
)

参数
name
类型:System..::.String

包含要获取的公共方法的名称的 String。

types
类型:array<System..::.Type>[]()[]

表示此方法要获取的参数的个数、顺序和类型的 Type 对象数组。

- 或 -

空的 Type 对象数组(由 EmptyTypes 字段提供),用来获取不采用参数的方法。

返回值
类型:System.Reflection..::.MethodInfo

表示其参数与指定参数类型匹配的公共方法的 MethodInfo 对象(如果找到的话);否则为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing)。

111,120

社区成员

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

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

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