您的位置:首页 > 编程语言 > C#

C# 程序集反射

2015-01-29 15:31 225 查看
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";
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: