(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,?
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
取得類型
。 ):
足球有四個 15 分鐘的季度
使用方法 CreateInstance():
足球有四個 15 分鐘的季度
四個 15 分鐘的季度
http://www.cnblogs.com/KissKnife/archive/2006/08/13 / 475717.html