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();
现在的问题是报错,如何调用重载的方法呢?

解决方案 »

  1.   

     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)。
      

  2.   

    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);