类里有SQLExecuteQueryCollection的多外重载,我想调用类的这个重载方法,试了半天,没有成功。1.用getMethod
2.用InvokeMemberpublic IList<T> SQLExecuteQueryCollection<T,Tparam>( string sqlStatement , Tparam t )
            where Tparam : class , new( )
            where T : class , new( )
        {}

解决方案 »

  1.   

    泛型方法在得到MethodInfo后,不能直接调用,需要设置泛型参数类型后才能调用,使用MethodInfo.MakeGenericMethod(Type[] types)方法设置所需要的泛型类型。
      

  2.   

    Hi qldsrx想问一下,如何能得到这个MethodInfo
    GetMethod("SQLExecuteQueryCollection",new Type[]{})type[]中的参数如何指定。谢谢。
      

  3.   


    你连最基本的反射都不会啊!假设这个函数所在的类叫SqlHelper
    那么得到这个函数的方法是:
    System.Reflection.MethodInfo method = typeof(SqlHelper).GetMethod("SQLExecuteQueryCollection");
    method = method.MakeGenericMethod(typeof(T), typeof(Tparam));
    method.Invoke(...);
    特别注意,这里面用的typeof(T), typeof(Tparam)并非实际类型,请实际使用时替换实际的类上去。
      

  4.   

    Hi qldsrxmethod = typeof(SqlHelper).GetMethod("SQLExecuteQueryCollection");
    报错:
    An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in mscorlib.dllAdditional information: Ambiguous match found.因为SQLExecuteQueryCollection有很多重载关键是string sqlStatement , Tparam t 这两个参数如何放到GetMethod中。
      

  5.   

    谢谢qldsrx!还是没弄出来,不过换了个实现方法:重新写一个SQLExecuteQueryCollection2,在SQLExecuteQueryCollection2中调用SQLExecuteQueryCollection。
    这样就不会有重载的函数了。
    System.Reflection.MethodInfo method = typeof(SqlHelper).GetMethod("SQLExecuteQueryCollection2");
    method = method.MakeGenericMethod(typeof(T), typeof(Tparam));
    method.Invoke(...);
      

  6.   

    如果是很多重载,可以用GetMethods方法先获取所有的方法,然后再过滤名称和内部一些细节如参数类型个数等。你可以调试下泛型方法的参数类型是什么。