C# 程序集反射

namespace AssemblyLibrary
{
    public class AssemblyLibrary
    {
        public static object LoadAssembly(string filePath,string nameSpace,string typeName,string methodName,object[] parameters)
        {
            try
            {
                byte[] filesByte = File.ReadAllBytes(filePath);
                Assembly assembly = Assembly.Load(filesByte);
                System.Type[] types = assembly.GetTypes();
                foreach (System.Type dllType in types) 
                {
                    if (dllType.Namespace == nameSpace && dllType.Name == typeName)
                    {
                        Type type = assembly.GetType(nameSpace + "." + typeName);
                        object obj = System.Activator.CreateInstance(type);
                        MethodInfo methodInfo = type.GetMethod(methodName);
                        if (methodInfo != null)
                        {
                            return methodInfo.Invoke(obj, parameters);
                        }
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
private void btnExecte_Click(object sender, EventArgs e)
{
     try
       {
             if (this.txtPathFile.Text.Trim() == "")
             {
                    MessageBox.Show("请输入相关查询条件!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    return;
             }
                object obj = AssemblyLibrary.AssemblyLibrary.LoadAssembly(this.txtPathFile.Text,"TestLibrary", "TestLibrary", "GetMethod", new object[] { this.txtParameters.Text }); 
          if (obj != null) { MessageBox.Show(obj.ToString(), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Question); }
   }
  
catch (Exception ex)
   {
      MessageBox.Show(ex.Message,
"异常提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
  }
}
namespace TestLibrary
{
    public class TestLibrary
    {
        public string GetMethod(string parm)
        {
            switch (parm)
            {
                case "1":
                    return "11111111";
                case "2":
                    return "22222222";
                case "3":
                    return "33333333";
                default:
                    return "00000000";
            }
        }
    }
}

 

posted @ 2015-01-29 15:31  如.若  阅读(266)  评论(0)    收藏  举报