博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

.NET反射的简单示例

Posted on 2007-07-03 15:40  徐正柱-  阅读(207)  评论(0编辑  收藏  举报
(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