(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
Word教程网 | Excel教程网 | Dreamweaver教程网 | Fireworks教程网 | PPT教程网 | FLASH教程网 | PS教程网 |
HTML教程网 | DIV CSS教程网 | FLASH AS教程网 | ACCESS教程网 | SQL SERVER教程网 | C语言教程网 | JAVASCRIPT教程网 |
ASP教程网 | ASP.NET教程网 | CorelDraw教程网 |