在TestAssembly命名空间下创建一个Person类,结构如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestAssembly
{
public class Person
{
public void Say ()
{
Console.WriteLine("Person Say!");
}
public void Say (string str)
{
Console.WriteLine("Person Say : " + str);
}
private void Eat ()
{
Console.WriteLine("Person Eat");
}
}
}
编译生成程序集,放到E盘.
新建项目,动态加载并使用TestAssembly.代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace UseAssembly
{
class Program
{
static void Main(string[] args)
{
string namespaceName = "TestAssembly";
string className = "Person";
string methodName = "Say";
string assemblyPath = @"E:\TestAssembly.exe";
//加载程序集
Assembly assem = Assembly.LoadFrom(assemblyPath);
//获取Person类
//Type personTp = assem.GetType(className); //null
Type personTp = assem.GetType(namespaceName + "." + className);
//创建对象
object person = Activator.CreateInstance(personTp);
//获取无参Say方法
//MethodInfo sayWithoutPar = personTp.GetMethod(methodName);//不明确的匹配,引发异常
MethodInfo sayWithoutPar = personTp.GetMethod(methodName, new Type[0]);
sayWithoutPar.Invoke(person, null);
//获取有参Say方法
MethodInfo sayWithPar = personTp.GetMethod(methodName, new Type[] { typeof(string) });
sayWithPar.Invoke(person, new object[] { "sayWithoutPar.Invoke" });
}
}
}
打印结果:
注意:
1.通过程序集获取指定类型时,GetType中的类名要指定命名空间,否则获取不到.
2.重载方法的获取,要在GetMethod中指定参数数量及类型,否则会引发异常.