本次项目使用VISUAL STUDIO 2013 演示,如果使用其他版本的话,可能会有一些不同,本文也具有参考价值,
祝大家的在技术的海洋里愉快的畅游
希望大家帮忙点点赞
1.使用VS2013新建一个类库,在类库中新建UserRobot类并且提添加方法sayGoodbye,返回字符串实例如下:Goodbye,如下图:
public class UserRobot
{
public string sayGoodbye()
{
return "Goodbye";
}
}
2.然后我们在新构建一个winfrom程序,用来调用UserRobot类中的方法sayGoodbye,并输出方法中返回的字符串:如下图:
3.现在调用代码如下
private void button1_Click(object sender, EventArgs e)
{
string path=@"D:\project\WindowsFormsApplication8\ClassLibrary1\bin\Debug\ClassLibrary1.dll";
Assembly assm=Assembly.LoadFile(path);
Type[] types=assm.GetTypes();
foreach(Type tp in types)
{
if(tp.Name=="UserRobot")
{
//获取不带参数的构造函数
ConstructorInfo mi=tp.GetConstructor(Type.EmptyTypes);
//获取类的UserRobot实例
object miclass=mi.Invoke(new object[]{});
MethodInfo md=tp.GetMethod("sayGoodbye");
//调用方法,下面是无参数的,如果有参数,//需要把null替换为参数的集合
object result=md.Invoke(miclass,null);
MessageBox.Show(result.ToString());
}
}
}
特别注意:使用的时候千万不要添加命名空间:System.Reflection;,要不然报错的哟,
希望对大家有所帮助