c# 反射调用类方法

zhq3k 2012-05-14 10:19:14
类里有SQLExecuteQueryCollection的多外重载,我想调用类的这个重载方法,试了半天,没有成功。

1.用getMethod
2.用InvokeMember

public IList<T> SQLExecuteQueryCollection<T,Tparam>( string sqlStatement , Tparam t )
where Tparam : class , new( )
where T : class , new( )
{

}

...全文
433 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
qldsrx 2012-05-14
  • 打赏
  • 举报
回复
泛型方法在得到MethodInfo后,不能直接调用,需要设置泛型参数类型后才能调用,使用MethodInfo.MakeGenericMethod(Type[] types)方法设置所需要的泛型类型。
qldsrx 2012-05-14
  • 打赏
  • 举报
回复
如果是很多重载,可以用GetMethods方法先获取所有的方法,然后再过滤名称和内部一些细节如参数类型个数等。你可以调试下泛型方法的参数类型是什么。
zhq3k 2012-05-14
  • 打赏
  • 举报
回复
谢谢qldsrx!

还是没弄出来,不过换了个实现方法:

重新写一个SQLExecuteQueryCollection2,在SQLExecuteQueryCollection2中调用SQLExecuteQueryCollection。
这样就不会有重载的函数了。
System.Reflection.MethodInfo method = typeof(SqlHelper).GetMethod("SQLExecuteQueryCollection2");
method = method.MakeGenericMethod(typeof(T), typeof(Tparam));
method.Invoke(...);
zhq3k 2012-05-14
  • 打赏
  • 举报
回复
Hi qldsrx

method = typeof(SqlHelper).GetMethod("SQLExecuteQueryCollection");
报错:
An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in mscorlib.dll

Additional information: Ambiguous match found.

因为SQLExecuteQueryCollection有很多重载

关键是string sqlStatement , Tparam t 这两个参数如何放到GetMethod中。
qldsrx 2012-05-14
  • 打赏
  • 举报
回复

你连最基本的反射都不会啊!

假设这个函数所在的类叫SqlHelper
那么得到这个函数的方法是:
System.Reflection.MethodInfo method = typeof(SqlHelper).GetMethod("SQLExecuteQueryCollection");
method = method.MakeGenericMethod(typeof(T), typeof(Tparam));
method.Invoke(...);

特别注意,这里面用的typeof(T), typeof(Tparam)并非实际类型,请实际使用时替换实际的类上去。
zhq3k 2012-05-14
  • 打赏
  • 举报
回复
Hi qldsrx

想问一下,如何能得到这个MethodInfo
GetMethod("SQLExecuteQueryCollection",new Type[]{})

type[]中的参数如何指定。

谢谢。

111,126

社区成员

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

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

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