(1)namespace classlibrarysport
{
public abstract class sport
{
protected string name;
public abstract string getname();
public abstract string getduration();
}
}
= = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = =
(2)namespace classlibrarysomesports//该项目添加了对(1)的引用
{
public class football : classlibrarysport.sport
{
public football()
{
name = “football”;
}
public override string getname()
{
return name;
}
public override string getduration()
{
return “four 15 minute quarters”;
}
}
}
= = = = = == = == = == = == = == = == = == = == = == = == = == = == = == = == = == = =
(3)namespace consoleassemblytest//该项目添加了对(1)的引用
{
class program
{
static void main(string[] args)
{
assembly assembly = assembly.loadfrom(@”e:\classlibrarysomesports\
bin\debug\classlibrarysomesports.dll”);
type[] types = assembly.gettypes();
console.writeline(“get type from classlibrarysomesports.dll:”);
for (int i = 0; i < types.length; i++)
{
console.writeline(types[i].name);
}
//使用getconstructor()方法获取对应类型的构造器,从而构造出该类型的对象
console.writeline(“use method getconstructor():”);
constructorinfo ci = types[0].getconstructor(new type[0]);
classlibrarysport.sport sport = (classlibrarysport.sport)ci.invoke(new object[0]);
console.writeline(sport.getname() + ” has ” + sport.getduration());
//使用activator.createinstance()方法构造出该类型的对象
//使用assembly.createinstance()返回为null,??
console.writeline(“use method createinstance():”);
classlibrarysport.sport sport1 = (classlibrarysport.sport)
activator.createinstance(types[0]);
console.writeline(sport1.getname() + ” has ” + sport1.getduration());
//反射指定类型中的名称为“getduration”的方法,通过invoke()方法执行该方法
object objsport = activator.createinstance(types[0]);
methodinfo method = types[0].getmethod(“getduration”);
object o = method.invoke(objsport, new object[0]);
console.writeline(o as string);
console.read();
}
}
}
= = = = = == = == = == = == = == = == = == = == = == = == = == = ==
output:
get type from classlibrarysomesports.dll:
football
use method getconstructor():
football has four 15 minute quarters
use method createinstance():
football has four 15 minute quarters
four 15 minute quarters
http://www.cnblogs.com/kissknife/archive/2006/08/13/475717.html