(1)命名空间ClassLibrarySport
{
public抽象类Sport
{
受保护的字符串名称;
公共抽象字符串 GetName();
公共抽象字符串 GetDuration();
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(2)namespace ClassLibrarySomeSports//该项目添加了对(1)的引用
{
public class Football : ClassLibrarySport.Sport
{
public Football()
{
name = "Football"; }
}
公共覆盖字符串 GetName()
{
返回名称;
}
public override string GetDuration()
{
return "四个 15 分钟的季度";
}
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = == = =
(3)namespace ConsoleAssemblyTest//该项目添加了对(1)的引用
{
class Program
{
static void Main(string[] args)
{
Assembly assembly = Assembly.LoadFrom(@"E:ClassLibrarySomeSports
bin DebugClassLibrarySomeSports.dll");
Type[] 类型 = assembly.GetTypes();
Console.WriteLine("从 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() + " 有 " + 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() + " 有 " + sport1.GetDuration());
// 引用指定类型中的名称为“GetDuration”的方法,通过Invoke()方法执行该方法
object objSport = Activator.CreateInstance(types[0]);
MethodInfo 方法 = types[0].GetMethod("GetDuration");
object o = method.Invoke(objSport, new object[0]);
Console.WriteLine(o 作为字符串);
控制台.Read();
}
}
}
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
输出:
从 ClassLibrarySomeSports 获取类型。 dll:
足球
使用方法 GetConstructor():
足球有四个 15 分钟的季度
使用方法 CreateInstance():
足球有四个 15 分钟的季度
四个 15 分钟的季度
http://www.cnblogs.com/KissKnife/archive/2006/08/13 /475717.html